【问题标题】:How to get SQL Join Output in the binary form如何以二进制形式获取 SQL 连接输出
【发布时间】:2017-07-21 14:03:05
【问题描述】:

我有 2 张桌子:

患者就诊表

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

第二张桌子是,

疾病表

 Disease ID Disease Name

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

我希望输出如下: 以患者 ID 为行,疾病为列的表格,二进制值表示哪个患者患有哪种疾病。

我应该使用什么查询?

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

【问题讨论】:

  • 这是用于 SQL Server 还是 MySQL?你在这个问题上有两个标签。
  • 搜索枢轴。对此有很多答案。
  • 这称为数据透视表,您可以在 SO 上找到 mysql 和 sql server 的答案。

标签: sql sql-server database tsql pivot


【解决方案1】:

如果您使用的是 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

【讨论】:

    【解决方案2】:

    试试这个

    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;
    

    【讨论】:

      猜你喜欢
      • 2012-11-14
      • 1970-01-01
      • 1970-01-01
      • 2011-03-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多