我有下表这些列TimeStamp [DateTime],FromSysId [Int],CrUSSDCnt [Int]
TimeStamp FromSysId CrUSSDCnt
2015-06-18 18:58:15.380 25 7
2015-06-18 19:45:17.130 21 8
2015-06-18 20:43:18.920 22 15
2015-06-18 21:34:33.090 25 6
2015-06-18 22:55:33.317 22 10
我希望将每个FromSysId显示为Column,同时计算每个FromSysId的CrUSSDCnt列并按小时分组TimeStime,如下所示:
TimeStamp Sys25 Sys22 Sys21
2015-06-18 18:00:00 2 1 0
2015-06-18 19:00:00 4 6 3
2015-06-18 20:00:00 0 5 6
2015-06-18 21:00:00 0 7 2
2015-06-18 22:00:00 1 0 4
我尝试使用pivot或Joint,但我都没有像这样总结。 任何帮助。
答案 0 :(得分:0)
这个问题的难点在于提取时间。这是一种方法:
select dateadd(hour, 0, datediff(hour, 0, timestamp)) as ToTheHour,
sum(case when FromSysId = 25 then CrUSSDCnt else 0 end) as Sys25,
sum(case when FromSysId = 22 then CrUSSDCnt else 0 end) as Sys22,
sum(case when FromSysId = 21 then CrUSSDCnt else 0 end) as Sys21
from table t
group by dateadd(hour, 0, datediff(hour, 0, timestamp))
order by ToTheHour;
其余的只是条件聚合。