2011-11-28 68 views
3

我正在寻找使用datepart运行SQL查询将数据分成小时增量,然后使该查询运行多天。目前,我只是将日期递增一天,然后运行多个查询。我想知道是否有一种方法可以将这一切合并为一个查询,以便为整个日期范围提供输出。SQL Server - 按小时查询多天

select datepart(hour, datetime), sum(calls) 
from dbo.gateway_concurrent_calls 
where datetime between 'MM/DD/YY' and 'MM/DD+1/YY' 
group by datepart(hour, datetime) 

这给出了这个输出。

0 1220 
1 569 
2 391 
3 313 
4 161 
5 68 
6 42 
7 24 
8 19 
9 18 
10 23 
11 45 
12 90 
13 311 
14 566 
15 668 
16 688 
17 735 
18 718 
19 729 
20 701 
21 699 
22 683 
23 570 

回答

7

集团双方的日期和时间:

select convert(date, datetime), datepart(hour, datetime), sum(calls) 
from dbo.gateway_concurrent_calls 
where datetime between 'MM/DD/YY' and 'MM/DD+1/YY' 
group by convert(date, datetime), datepart(hour, datetime) 
+2

除非有什么我不知道的,转换应该看起来像'convert(date,datetime)'或像'cast(datetime as date)'。除此之外,它是+1。 –

1

这个查询将圆的datetime列到最接近的小时,同时保持日期部分也给你所寻求的结果,我相信:

select DATEADD(hour,DATEDIFF(hour,0,datetime),0), sum(calls) 
from dbo.gateway_concurrent_calls 
where datetime between @StartDate and @EndDate 
group by DATEADD(hour,DATEDIFF(hour,0,datetime),0) 

请注意,我假设开始和结束日期将提供作为变量/参数 - 如果你打算继续使用文字字符串,尝试使用格式YYYYMMDD(用于日期),例如今天是20111129 - 此格式在SQL Server的区域设置中是明确的。