Reputation: 3115
I have a hypothetical database comprised of patients and their comorbidities (or diagnosis codes as they are often termed):
PATIENT_ID | HOSPITAL | DIAG_01 | DIAG_02 | DIAG_03 | DIAG_04 ...up to Diag_14
Patient 1 | Hosp1 | C01 | C02 | NULL | NULL
Patient 2 | Hosp1 | A01 | A02 | A03 | P37
Patient 3 | Hosp2 | A01 | D10 | X01 | NULL
A patients comorbidities (there can be up to 14 of them recorded) define any illness/disease the patient may have. In particular C00 - C97 and D00 - D48 relate to Cancer ICD-10 codes.
I'd like to produce a summary for each Hospital which counts how many of their patients had a Cancer ICD-10 code in the diagnosis column.
Based on the example above, both Hosp1 and Hosp2 would have 1 patient each with Cancer. The C01 and C02 diagnosis codes for Patient 1 would only be counted as one patient with Cancer. However if Patient 1 was admitted again it would count as another case of a patient with Cancer.
I tried creating a table of all the Cancer comorbidities and using a JOIN query on all 14 of the diag columns but could not work out to do a count.
Any ideas or help would be massively, massively appreciated.
Upvotes: 0
Views: 928
Reputation: 67
Use union all
SELECT * FROM /**customize your select here could be count() etc **/
(SELECT PATIENT_ID,HOSPITAL,DIAGNOSIS
FROM (
SELECT PATIENT_ID, HOSPITAL, LEFT(DIAG_01,1) AS DIAGNOSIS FROM table_name WHERE DIAG_01 IS NOT NULL UNION ALL
SELECT PATIENT_ID, HOSPITAL, LEFT(DIAG_02,1) AS DIAGNOSIS FROM table_name WHERE DIAG_02 IS NOT NULL UNION ALL
SELECT PATIENT_ID, HOSPITAL, LEFT(DIAG_03,1) AS DIAGNOSIS FROM table_name WHERE DIAG_03 IS NOT NULL UNION ALL
SELECT PATIENT_ID, HOSPITAL, LEFT(DIAG_04,1) AS DIAGNOSIS FROM table_name WHERE DIAG_04 IS NOT NULL
) AS T1
GROUP BY PATIENT_ID,HOSPITAL,DIAGNOSIS
) AS T2
WHERE DIAGNOSIS IN ('C','D') /**where **/
Upvotes: 1
Reputation: 1269653
You have a bad data layout. You should have a junction table. But, you don't. You can do what you want with union all
:
select hospital, count(distinct patient_id)
from ((select patient_id, hospital, diag_01 as diag
from hypothetical
) union all
(select patient_id, hospital, diag_02 as diag
from hypothetical
)
union all
. . .
(select patient_id, hospital, diag_14 as diag
from hypothetical
)
) phd
where diag in ('C01', 'C02');
Upvotes: 1