SQL多个GROUP BY表示在一行中

时间:2015-12-28 21:48:10

标签: sql sql-server

这个问题是从SQL Server环境中提出的。我在这里找到了一些建议,用于创建包含多个GROUP BY条件的查询,但所有条件都基于第二组条件生成多行。例如,如果TrendingData表中的数据集如下所示:

ID  SEND    HL7 MessageControl                              STAT    DATE CREATED            DATE UPDATED
4   AMC1    A03 A03918604B6-4272-40E6-9178-1D711FB135461    P       2015-12-15 12:01:19.153 2015-12-15 12:01:20.137
5   AMC1    A08 A08918604B6-4272-40E6-9178-1D711FB135462    P       2015-12-15 12:01:20.137 2015-12-15 12:01:20.153
6   UHC1R   A08 A0893126369-10D1-4506-9A42-B9A7E0AC96151    R       2015-12-15 12:01:34.433 2015-12-15 12:01:34.497
7   UHC1R   A03 A03C2468021-8C66-4BAD-A6A7-CBCA02125D411    R       2015-12-15 12:02:38.293 2015-12-15 12:02:38.450
8   UHC1R   A08 A08C2468021-8C66-4BAD-A6A7-CBCA02125D412    P       2015-12-15 12:02:38.450 2015-12-15 12:02:38.760
9   UHC1    A08 A0863D0A3D8-402C-4377-9C77-63518A42A11D1    P       2015-12-15 12:02:42.730 2015-12-15 12:02:43.057

然后是查询结果

SELECT  
    COUNT(*) AS Counts,
    STAT,
    CONVERT(CHAR(5), DateCreated, 10) AS Date
FROM
    TrendingData
GROUP BY 
    STAT, CONVERT(CHAR(5), DateCreated, 10)
ORDER BY 
    Date;

返回类似的输出(这些数字来自整个表格的数据集,而不仅仅是上面的几行):

Counts  STAT    Date
4488    P       12-15
27568   R       12-15

但是我所拥有的输出看起来像是:

Total   CodeP   CodeR   Date
32056   4488    27568   12-15

我相当确定CodeP列会被count(*) from TrendingDate where STAT = 'P'的某个变体填充,但我似乎无法使语法正确以使查询拉出三在同一天内计算。

建议?

1 个答案:

答案 0 :(得分:2)

您只需在CASE汇总函数中使用COUNT语句查看PR计数,然后移除STAT列来自GROUP BY

SELECT  COUNT(*) AS Total,
        COUNT(CASE WHEN stat = 'P' THEN 1 END) AS CodeP,
        COUNT(CASE WHEN stat = 'R' THEN 1 END) AS CodeR,
        CONVERT(CHAR(5), DateCreated, 10) AS Date
FROM    TrendingData
GROUP BY CONVERT(CHAR(5), DateCreated, 10)
ORDER BY Date;