计算SQL Server中每小时的行数,并将结果作为完整的日期时间值

时间:2013-12-21 14:17:59

标签: sql sql-server

如何计算SQL Server中每小时的行数,并显示完整的日期时间。

我已经尝试了这个,但它只返回小时

SELECT DATEPART(HOUR,TimeStamp), Count(*)
FROM [TEST].[dbo].[data]
GROUP BY DATEPART(HOUR,TimeStamp)
ORDER BY DATEPART(HOUR,TimeStamp)

现在的结果是:

Hour   Occurrence 
----   ----------
10     2157
11     60740
12     66189
13     77096
14     90039

但我需要这个:

Timestamp               Occurrence
-------------------     ----------
2013-12-21 10:00:00     2157
2013-12-21 11:00:00     60740
2013-12-21 12:00:00     66189
2013-12-21 13:00:00     77096
2013-12-21 14:00:00     90039
2013-12-22 09:00:00     84838
2013-12-22 10:00:00     64238

1 个答案:

答案 0 :(得分:25)

您实际上需要将TimeStamp四舍五入到小时。在SQL Server中,这有点难看,但很容易做到:

SELECT dateadd(hour, datediff(hour, 0, TimeStamp), 0) as TimeStampHour, Count(*)
FROM [TEST].[dbo].[data]
GROUP BY dateadd(hour, datediff(hour, 0, TimeStamp), 0)
ORDER BY dateadd(hour, datediff(hour, 0, TimeStamp), 0);