SQL在不同条件下加入相同的表并获取计数

时间:2017-12-28 15:47:56

标签: sql sql-server join inner-join

我有一张保险索赔表。它有ID,患者有的条件,ClaimID,EmergencyDepartmentFlag(1 - ED; 0 - NonED。我需要得到的结果给出了每个条件的索赔计数和每个条件下ED就诊的次数

array = %w(first second third)

预期输出

+----------+-----------+----------+--------+
| MemberID | Condition | ClaimID  | EDFlag |
+----------+-----------+----------+--------+
| A123     | COPD      | 34124434 |      1 |
| A526     | COPD      | 34580304 |      0 |
| A693     | COPD      | 23723642 |      1 |
| A645     | DM        | 46534633 |      1 |
+----------+-----------+----------+--------+

查询

+-----------+-------------+----------+
| Condition | TotalClaims | EDClaims |
+-----------+-------------+----------+
| COPD      |           3 |        2 |
| DM        |           1 |        1 |
+-----------+-------------+----------+

此查询未返回正确的结果。

2 个答案:

答案 0 :(得分:3)

只需使用此

xaml.cs

演示:

SELECT
    Condition,
    TotalClaims = COUNT(1),
    EDClaims = SUM(CAST(EDFlag AS INT))
    FROM YourTable
    GROUP BY Condition

结果

enter image description here

答案 1 :(得分:1)

SELECT 
Condition,
COUNT(*) AS TotalClaims,
SUM(CASE WHEN EDFlag = 1 THEN 1 ELSE 0 END) AS EDClaims
FROM mytable
GROUP BY Condition