2017-03-02 32 views
0

我有2個表:如何獲得二進制格式的SQL JOIN輸出

患者就診表

Visit ID Patient ID Date Disease ID 
    101   1  22-Feb  11 
    102   5  5-Apr  22 
    103   3  2-Jul  77 
    104   2  4-Feb  55 
    105   6  5-Jan  99 
    106   2  6-Jan  66 
    107   2  8-Jan  77 
    108   7  9-Jan  44 
    109   5  22-Jan  88 
    110   1  23-Jan  33 

和第2表,

疾病表

Disease ID Disease Name 

     11 Asthama 
     22 TB 
     33 Flu 
     44 AIDS 
     55 Cancer 
     66 Heart Disease 
     77 ABC 
     88 XYZ 
     99 MNO 

我需要的輸出如下: 病人標識符爲Row和Disease爲列的表格,Th e二進制值指示哪個患者患有哪種疾病。

我應該使用什麼查詢?

The table with Patient ID as Row and Disease as columns, The binary values indicating which patient has which disease

+1

這是用於SQL Server或MySQL?你在這個問題上都有兩個標籤。 –

+1

搜索PIVOT。對此有很多答案。 – DVT

+1

這被稱爲數據透視表,你可以在SO上找到mysql和sql server的答案。 – Shadow

回答

0

如果您正在使用SQL Server試試這個,希望能幫助。使用Case Expression

select t1.patient_id, 
    case when t2.disease_name='Asthma' then 1 else 0 end as Asthma, 
    case when t2.disease_name='TB' then 1 else 0 end as TB, 
    case when t2.disease_name='Flu' then 1 else 0 end as Flu, 
    case when t2.disease_name='AIDS' then 1 else 0 end as AIDS, 
    case when t2.disease_name='Cancer' then 1 else 0 end as Cancer, 
    case when t2.disease_name='Heart Disease' then 1 else 0 end as 'Heart Disease', 
    case when t2.disease_name='ABC' then 1 else 0 end as ABC, 
    case when t2.disease_name='XYZ' then 1 else 0 end as XYZ, 
    case when t2.disease_name='MNO' then 1 else 0 end as MNO 
from #table1 t1 
left join #table2 t2 
on t1.Disease_id=t2.Disease_id 
order by t1.patient_id 
0

試試這個

SELECT PatientID, [Asthama],[TB],[Flu],[AIDS],[Cancer],[Heart Disease], [ABC],[XYZ],[MNO] 
FROM 
(SELECT P.PatientID,D.Disease from Patient P inner join Disease D on  P.DiseaseID=D.DiseaseID) AS SourceTable 
PIVOT 
(
count(Disease) 
FOR Disease IN ([Asthama],[TB],[Flu],[AIDS],[Cancer],[Heart Disease],[ABC],[XYZ],[MNO]) 
) AS PivotTable;