各种总和,按建立分组

时间:2015-04-30 14:30:47

标签: sql-server sql-server-2008 tsql group-by

我有以下查询,但我无法弄清楚如何获得所需的结果集。

我需要这些确切的信息,但仅按照“建立”进行分组,以便每一行都有一个“机构”和一个适当的总和,并计算该特定机构的数量。我的查询给了我所有正确的数字,除了它还使我按照typeg,wdl和wdlr组成,这为每个机构创建了多行。

SELECT
    '2014' ,
    t6.Establishment AS 'establishment id' ,
    CASE WHEN wdl > 0 THEN COUNT(wdl) END AS 'Days away cases' ,
    CASE WHEN wdlr > 0 THEN COUNT(wdlr) END AS 'Days transfer cases' ,
    SUM(WDL) AS 'days away',
    SUM(wdlr) AS 'transfer days',
    CASE WHEN typeG = 1 THEN COUNT(typeG) END AS 'Injury Count'
FROM
    cairs.gics t1
LEFT JOIN 
    lkuEstablishment t6 ON t1.org = t6.org
WHERE
    Establishment IS NOT NULL
GROUP BY
    Establishment ,
    t1.typeG ,
    t1.WDL ,
    t1.WDLR;

1 个答案:

答案 0 :(得分:3)

您没有正确使用CASE表达式。您应该在聚合函数中使用它们:

SELECT  '2014',
        t6.Establishment as [establishment id], 
        SUM(CASE WHEN wdl > 0 THEN 1 ELSE 0 END) as [Days away cases],
        SUM(CASE WHEN wdlr > 0 THEN 1 ELSE 0 END) as [Days transfer cases],
        SUM(WDL) as [days away], 
        SUM(wdlr) as [transfer days],
        SUM(CASE WHEN typeG = 1 THEN 1 ELSE 0 END) as [Injury Count]
FROM cairs.gics t1
LEFT JOIN lkuEstablishment t6 
    ON t1.org = t6.org
WHERE Establishment IS NOT NULL
GROUP BY t6.Establishment;