根据小时聚合时间数据

fir*_*ger 3 t-sql sql-server

我在MSSQL中有一个表,其中两列看起来像下面的示例.我想弄清楚会话时间内所有小时的行数.

Session Time          Duration
2011-06-09 23:47:07   00:01:51
2011-06-09 23:54:45   00:12:37
2011-06-09 23:41:17   00:21:57
2011-06-09 23:41:54   00:34:35
2011-06-09 22:47:51   00:01:20
2011-06-09 22:56:04   00:09:33
2011-06-09 22:55:40   00:11:08
2011-06-09 22:47:30   00:05:06
Run Code Online (Sandbox Code Playgroud)

最后,结果看起来像这样:

Session Time          Number of Records
2011-06-09 23:00:00   4
2011-06-09 22:00:00   4
Run Code Online (Sandbox Code Playgroud)

Mik*_*son 5

-- Test data
;with YourTable([Session Time]) as
(
select cast('2011-06-09 23:47:07' as datetime) union all
select '2011-06-09 23:54:45' union all
select '2011-06-09 23:41:17' union all
select '2011-06-09 23:41:54' union all
select '2011-06-09 22:47:51' union all
select '2011-06-09 22:56:04' union all
select '2011-06-09 22:55:40' union all
select '2011-06-09 22:47:30'
)

-- Query
select dateadd(hh, datediff(hh, 0, [Session Time]), 0) as [Session Time],
       count(*) as [Number of Records]
from YourTable
group by dateadd(hh, datediff(hh, 0, [Session Time]), 0)
Run Code Online (Sandbox Code Playgroud)