按几列分组,并在另一列SQL Server上计数

时间:2018-12-19 09:49:05

标签: sql sql-server group-by count pivot

我正在使用SQL SERVER 2012,并且在处理此SQL语句。基本上我有这张桌子

table

我想按日期和用户名分组,并在状态列上进行计数,如下所示:

query result

我该如何实现?

3 个答案:

答案 0 :(得分:1)

您可以对几个条件SUM使用联合查询。

SELECT 
    LastUpdate,
    UpdatedBy as User, 
    SUM(CASE WHEN Status = 'A' THEN 1 ELSE 0 END) as A
    SUM(CASE WHEN Status = 'C' THEN 1 ELSE 0 END) as C
    SUM(CASE WHEN Status = 'D' THEN 1 ELSE 0 END) as D
    SUM(CASE WHEN Status = 'Z' THEN 1 ELSE 0 END) as Z
    SUM(CASE WHEN Status = 'X' THEN 1 ELSE 0 END) as X
FROM table
GROUP BY LastUpdate, UpdatedBy
ORDER BY LastUpdate, UpdatedBy

答案 1 :(得分:1)

您可以尝试使用条件聚合

select LastUpdate,UpdatedBy, 
count(case when Status='A' then UpdatedBy end) as 'A',
count(case when Status='C' then UpdatedBy end) as 'C',
count(case when Status='D' then UpdatedBy end) as 'D',
count(case when Status='Z' then UpdatedBy end) as 'Z',
count(case when Status='X' then UpdatedBy end) as 'X'
from tablename
group by LastUpdate,UpdatedBy

答案 2 :(得分:0)

好吧,我在伙计们的回答下弄清楚了

    SELECT 
    CAST(LastUpdate as DATE),
    UserName,
    SUM(CASE WHEN Status = 1 THEN 1 ELSE 0 END) as [Status_1],
    SUM(CASE WHEN Status = 2 THEN 1 ELSE 0 END) as [Status_2],
    SUM(CASE WHEN Status = 3 THEN 1 ELSE 0 END) as [Status_3]
FROM Table
WHERE LastUpdate BETWEEN '2018-11-30 10:013:44.080' AND '2018-12-30 10:013:44.080'
    GROUP BY CAST(LastUpdate as DATE), UserName
    ORDER BY CAST(LastUpdate as DATE)

这是一个示例查询,我在其中查找两个日期之间的记录。我遇到的问题部分是由于过滤了datetime而不是date。 lastupdate列是一个日期时间,因此通过强制转换日期可以解决问题