使用左外连接的每个ID的SQL组行

时间:2017-10-20 18:16:56

标签: sql sql-server join left-join distinct

我有一张表,其中包括糖尿病,高血压,心力衰竭等6种不同病症的近百万份索赔记录。每个成员都有一些索赔。他可能会声称患有糖尿病或高血压或其他任何疾病。我的目标是按照每个成员行对他们拥有的条件(索赔数量)进行分组。

现有表格

+--------------+---------------+------+------------+
|  Conditions  | ConditionCode |  ID  | Member_Key |
+--------------+---------------+------+------------+
| DM           |          3001 | 1212 | A1528      |
| HTN          |          5001 | 1213 | A1528      |
| COPD         |          6001 | 1214 | A1528      |
| DM           |          3001 | 1215 | A1528      |
| CAD          |          8001 | 1823 | B4354      |
| HTN          |          5001 | 3458 | B4354      |
+--------------+---------------+------+------------+

期望的结果

+------------+------+-----+----+----+-----+-----+
| Member_Key | COPD | CAD | DM | HF | CHF | HTN |
+------------+------+-----+----+----+-----+-----+
| A1528      |    1 |     |  2 |    |     |   1 |
| B4354      |      |   1 |    |    |     |   1 |
+------------+------+-----+----+----+-----+-----+

查询

select distinct tr.Member_Key,C.COPD,D.CAD,DM.DM,HF.HF,CHF.CHF,HTN.HTN
   FROM myTable tr
   --COPD
  left outer join (select Member_Key,'X' as COPD
   FROM myTable
   where Condition=6001) C
  on C.Member_Key=tr.Member_Key
  --CAD
  left outer join ( ....

现在我只是使用' X'。但我试图根据条件获得代替X的索赔数量。我不认为使用左外连接是有效的,当你搜索100万行并做一个独特的。你有任何其他方法来解决这个问题吗?

3 个答案:

答案 0 :(得分:4)

您不需要这么多子查询,使用group by和case语句很容易:

SELECT Member_Key
       SUM(CASE WHEN Condition=6001 THEN 1 ELSE 0 END) AS COPD,              
       SUM(CASE WHEN Condition=3001 THEN 1 ELSE 0 END) AS DM,
       SUM(CASE WHEN Condition=5001 THEN 1 ELSE 0 END) AS HTN,
       SUM(CASE WHEN Condition=8001 THEN 1 ELSE 0 END) AS CAD
FROM myTable
GROUP BY Member_Key

答案 1 :(得分:2)

这是CASE声明的理想情况:

SELECT tr.Member_Key, 
    SUM(CASE WHEN Condition=6001 THEN 1 ELSE 0 END) as COPD,
    SUM(CASE WHEN Condition=6002 THEN 1 ELSE 0 END) as OtherIssue,
    SUM(CASE etc.)
FROM myTable tr
GROUP BY tr.Member_Key

答案 2 :(得分:0)

这应该通过PIVOT来完成,例如:

SELECT *
FROM
(SELECT conditions, member_key
 FROM t) src
 PIVOT
(COUNT (conditions)
 for conditions in ([COPD], [CAD], [DM], [HF], [CHF], [HTN])) pvt