T-SQL Group by DateTime

时间:2015-06-30 12:21:11

标签: sql sql-server tsql

我有以下T-SQL查询,我想在日期的每个小时选择系统21的计数:

Select DATEADD (HOUR,DATEDIFF (HOUR,0,TimeStamp),0) [Date],
Case when System= 21 then Count(CurUSSDCnt) else 0 end as Sys21
from table
group by DATEADD (HOUR,DATEDIFF (HOUR,0,TimeStamp),0) ,System
order by [Date];

输出将返回如下内容:

Date                    Sys21
2015-06-29 00:00:00.000 0
2015-06-29 00:00:00.000 0
2015-06-29 00:00:00.000 0
2015-06-29 00:00:00.000 0
2015-06-29 00:00:00.000 0
2015-06-29 00:00:00.000 0
2015-06-29 00:00:00.000 3552
2015-06-29 00:00:00.000 0
2015-06-29 00:00:00.000 0
2015-06-29 00:00:00.000 0
2015-06-29 00:00:00.000 0
2015-06-29 00:00:00.000 0
2015-06-29 00:00:00.000 0
2015-06-29 01:00:00.000 0
2015-06-29 01:00:00.000 0
2015-06-29 01:00:00.000 0
2015-06-29 01:00:00.000 0
2015-06-29 01:00:00.000 0
2015-06-29 01:00:00.000 0
2015-06-29 01:00:00.000 0
2015-06-29 01:00:00.000 0
2015-06-29 01:00:00.000 0
2015-06-29 01:00:00.000 0
2015-06-29 01:00:00.000 0
2015-06-29 01:00:00.000 1880
2015-06-29 01:00:00.000 0

而不是:

Date                    Sys21
2015-06-29 00:00:00.000 3552
2015-06-29 01:00:00.000 1880

2 个答案:

答案 0 :(得分:2)

如果您只需要有关系统21的信息,则需要WHERE子句,而不是CASE表达式:

Select DATEADD (HOUR,DATEDIFF (HOUR,0,TimeStamp),0) [Date],
 Count(CurUSSDCnt) as Sys21
from table
where System= 21
group by DATEADD (HOUR,DATEDIFF (HOUR,0,TimeStamp),0)
order by [Date];

如果您需要更多系统,请使用ughai's answer中显示的手动数据透视或使用PIVOT

select TimeHour,[21] as Sys21,[22] as Sys22
from
   (select System,
           DATEADD(hour,DATEDIFF(hour,0,TimeStamp),0) as TimeHour,
           CurUSSDCnt
    from table
    ) t
       PIVOT (COUNT(CurUSSDCnt) for System in ([21],[22])) u

(如果PIVOT列表不是详尽无遗的,您可能需要在子选择中添加WHERE子句:

   (select System,
           DATEADD(hour,DATEDIFF(hour,0,TimeStamp),0) as TimeHour,
           CurUSSDCnt
    from table
    where System in (21,22)) t

答案 1 :(得分:1)

您应该将count放在CASE之外。即使System= 21记录不存在,也会显示所有小时数。我还将COUNT更改为SUM

Select DATEADD (HOUR,DATEDIFF (HOUR,0,TimeStamp),0) [Date],
SUM(Case when System= 21 then CurUSSDCnt else 0 end) as Sys21
from table
group by DATEADD (HOUR,DATEDIFF (HOUR,0,TimeStamp),0)
order by DATEADD (HOUR,DATEDIFF (HOUR,0,TimeStamp),0);

如果您只想要System= 21的那些小时,请使用Damien_The_UnBeliever建议的WHERE条款