我有一个表记录应用程序活动。 每行包含一个DateTime(“Time”)和一个“EventType”列......(显然其他一些在这里并不重要)
我希望能够计算每小时发生的不同EventType的数量。
我目前正在获得单个EventType的基本计数:
select DATEADD(hh, (DATEDIFF(hh,0,Time)),0) as 'hour', count(*) as 'apploads'
from PlaySessionEvent
where EventType = 0
Group By DATEADD(hh,(DATEDIFF(hh,0,Time)),0)
order by hour
扩展此功能以便在同一小时内计算多个不同的EventTypes的最简单方法是什么?
::更新
应该已经指定,我不仅仅按EventType分组,因为我只想要所有可用的EventType的子集。 (即没有无聊的跟踪/调试数据) 此外,我希望将不同的事件类型作为列,而不是复制DateTime条目的其他行。
...例如
DateTime EventType1 EventType2
12:12:12 12/12/12 45 22
对不准确的初始问题抱歉!
答案 0 :(得分:4)
select EventType, DATEADD(hh, (DATEDIFF(hh,0,Time)),0) as 'hour', count(*) as 'apploads'
from PlaySessionEvent
where EventType = 0
Group By DATEADD(hh,(DATEDIFF(hh,0,Time)),0), EventType
order by hour
编辑:
更改问题的新解决方案:
select DATEADD(hh, (DATEDIFF(hh,0,Time)),0) as 'hour', count(*) as 'apploads',
sum(case when EventType = 1 then 1 else 0 end) EventType1,
sum(case when EventType = 2 then 1 else 0 end) EventType2
from PlaySessionEvent
where EventType = 0
group By DATEDIFF(hh,0,Time)
order by hour
这是一种略有不同的写作方式:
select DATEADD(hh, (DATEDIFF(hh,0,Time)),0) as [hour],
COUNT(*) [apploads],
COUNT(case when EventType = 1 then 1 end) EventType1,
COUNT(case when EventType = 2 then 1 end) EventType2
from PlaySessionEvent
where EventType = 0
group By DATEDIFF(hh,0,Time)
order by hour