我有一个包含2628行的表。我想每小时计数一次。我有一个completion_time
列,它告诉每条记录的日期时间。
我只能找到一个小时的时间。
select count(*)
from billing b
where b.completion_time >= '2019-04-16 23:50:23'
and b.completion_time <='2019-04-17 00:50:22'
日期时间最多为9小时。即该过程始于2016-04-16 23:50:23
,结束于2019-04-17 08:16:49
。所以我想要每小时的总计数。
更新1
我想要类似下面的输出
如何实现?任何帮助将不胜感激。
答案 0 :(得分:3)
尝试一下:
select datepart(hour,b.completion_time) Hour, count(*) NumberOfRecords
from billing b
group by datepart(hour,b.completion_time)
修改:
select row_number() over (order by min(b.completion_time)) RowNumber, count(*) NumberOfRecords
from billing b
group by datepart(hour,b.completion_time)
order by min(b.completion_time)
答案 1 :(得分:0)
尝试一下。
Declare @StartTime DATETIME = '2016-04-16 23:50:23'
Declare @EndTime DateTime = '2019-04-17 08:16:49'
Declare @Tab Table(id int, Completion_Time DateTime)
Insert into @Tab
SELECT 1, '2016-04-16 23:50:23' Union All
SELECT 2,'2016-04-17 00:50:24' Union All
SELECT 3,'2016-04-17 01:50:26' Union All
SELECT 4,'2016-04-17 01:50:32' Union All
SELECT 5,'2016-04-17 01:50:55' Union All
SELECT 6,'2016-04-17 02:50:28' Union All
SELECT 7,'2016-04-17 02:50:30' Union All
SELECT 8,'2016-04-17 02:50:45' Union All
SELECT 9,'2016-04-17 04:50:32' Union All
SELECT 10,'2016-04-17 04:50:52'
--Select Id, DATEDIFF(HH,@StartTime,Completion_Time) Diff from @Tab
;with cte
As
(
SELECT CONVERT(VARCHAR(5),DATEDIFF(HH,@StartTime,Completion_Time)+1) as [Hour] , COUNT(*) As [Records]
From @Tab
Group by DATEDIFF(HH,@StartTime,Completion_Time)+1
)
Select [Hour] + CASE
WHEN [Hour] % 100 IN (11,12,13) THEN 'th'
WHEN [Hour] % 10 = 1 THEN 'st'
WHEN [Hour] % 10 = 2 THEN 'nd'
WHEN [Hour] % 10 = 3 THEN 'rd'
ELSE 'th'
END + ' hour',
Records
from cte
答案 2 :(得分:-1)
这将满足您的需求:
SELECT HOUR(b.completion_time) hourOfDay, COUNT(*) NumberOfRecords
FROM billing b
GROUP BY hourOfDay
HOUR
是预定义的函数,用于根据DateTime
计算小时。