如何按日期时间列对自定义小时进行分组

时间:2013-01-05 06:47:13

标签: sql sql-server

如何按日期时间列分组自定义小时,例如每5小时或每12小时或每24小时。

Select CreateOn, Count(*) From Table1
Group By ?????

2 个答案:

答案 0 :(得分:2)

您应该在此示例中选择开始日期/时间“2011-01-01”,然后使用DATEDIFF() function获取开始日期与CreateOn之间的小时差异。然后使用/运算符获取整数区间数(在此示例中为5小时)。

Select 
min(DATEADD(HOUR,DATEDIFF (HOUR,'2011-01-01',CreateOn )/5*5,'2011-01-01')) 
   as Start_time,
max(DATEADD(HOUR,(DATEDIFF (HOUR,'2011-01-01',CreateOn )/5+1)*5,'2011-01-01')) 
   as End_Time,
DATEDIFF (HOUR,'2011-01-01',CreateOn )/5 as Interval_Number, 
Count(*) as _Count
From Table1
Group By DATEDIFF (HOUR,'2011-01-01',CreateOn )/5

答案 1 :(得分:1)

如果我理解你的问题,你可以尝试这样的事情:

SELECT CreateOn, Count(*) FROM Table1 GROUP BY (DATEPART(MINUTE, [Date]) % 12)