无论白天,T-SQL每小时​​都能获得一次

时间:2017-01-24 15:15:43

标签: sql sql-server tsql

使用在这篇文章Count rows per hour in SQL Server with full date-time value as result中找到的接受的答案我能够按小时计算记录数,但是,我想这样做以便当天无关紧要。

如何记录当天的小时数,无论记录来自哪一天?

例如,下表:

+----------+-------------------------+
| instance |        datetime         |
+----------+-------------------------+
| A        | 2017-01-10 11:01:05.267 |
| B        | 2017-01-13 11:07:05.783 |
| C        | 2017-01-14 11:37:05.593 |
| D        | 2017-01-17 11:37:38.610 |
| E        | 2017-01-17 11:47:04.877 |
| F        | 2017-01-15 12:14:34.127 |
| G        | 2017-01-17 12:15:09.373 |
| H        | 2017-01-09 13:58:06.013 |
+----------+-------------------------+

会产生以下数据集:

+-------------+-------------+
| recordCount |  timeStamp  |
+-------------+-------------+
|           5 | 11:00:00.00 |
|           2 | 12:00:00.00 |
|           1 | 13:00:00.00 |
+-------------+-------------+

2 个答案:

答案 0 :(得分:6)

您可以使用DATEPART

SELECT DATEPART(HOUR, [datetime]), COUNT(*)
FROM mytable
GROUP BY DATEPART(HOUR, [datetime])

该函数返回一个整数,实质上是从DATETIME字段中提取小时值。

答案 1 :(得分:1)

如果您使用的是SQL SERVER 2012或更高版本,请使用FORMAT

SELECT Count(1) AS Recordcount,
       Format([datetime], 'HH:00:00')
FROM   yourtable
GROUP  BY Format([datetime], 'HH:00:00') 

CONCATDATEPART

SELECT Concat(Datepart(HOUR, [datetime]), ':00:00'),
       Count(*)
FROM   Yourtable
GROUP  BY Datepart(HOUR, [datetime])