SQL中的日期范围高级计数计算

时间:2012-10-19 10:47:05

标签: sql-server tsql date-range

我正致力于呼叫中心项目,我必须在特定时间范围内同时计算呼叫到达时间。 我必须编写一个具有参数StartTime,EndTime和Interval

的过程

例如:

Start Time: 11:00
End Time: 12:00
Interval: 20 minutes

所以程序应该将1小时的时间范围分成3个部分,每个部分应该计算在此范围内开始和结束的到达时间或已开始但尚未完成的到达时间

应该是这样的:

11:00 - 11:20 15 calls at the same time(TimePeaks)
11:20 - 11:40 21 calls ...
11:40 - 12:00  8 calls ...

有关如何计算它们的任何建议吗?

2 个答案:

答案 0 :(得分:2)

您可以使用DATEADDGROUP BY您的时间跨度:

Select Count(*), DateAdd(Minute, @Interval * (DateDiff(Minute, 0, SomeDate) / @Interval), 0)As Part
From #Temp
Where SomeDate Between @StartTime And @EndTime
Group By DateAdd(Minute, @Interval * (DateDiff(Minute, 0, SomeDate) / @Interval), 0)
ORDER BY Part 

示例数据:

declare @StartTime datetime;
declare @EndTime datetime;  
declare @Interval int;
SET @StartTime = Convert(datetime,'2012-10-19 12:00:00',102);
SET @EndTime = Convert(datetime,'2012-10-19 13:00:00',102);
SET @Interval = 20;

create table #Temp(SomeDate datetime);
insert into #Temp values(Convert(datetime,'2012-10-19 12:05:00',102));
insert into #Temp values(Convert(datetime,'2012-10-19 12:06:00',102));
insert into #Temp values(Convert(datetime,'2012-10-19 12:15:00',102));
insert into #Temp values(Convert(datetime,'2012-10-19 12:25:00',102));
insert into #Temp values(Convert(datetime,'2012-10-19 12:45:00',102));
insert into #Temp values(Convert(datetime,'2012-10-19 12:35:00',102));
insert into #Temp values(Convert(datetime,'2012-10-19 12:37:20',102));
insert into #Temp values(Convert(datetime,'2012-10-19 12:15:00',102));
insert into #Temp values(Convert(datetime,'2012-10-19 12:55:00',102));
insert into #Temp values(Convert(datetime,'2012-10-19 12:18:10',102));

这是一个小提琴:http://sqlfiddle.com/#!3/ee6f9/1/0

答案 1 :(得分:1)

寻找1小时前的范围:

DECLARE @iniz VARCHAR(16), @fine VARCHAR(16), @ades VARCHAR(16)
SET @iniz = convert(varchar(16), dateadd(mi,-(60+(datepart(mi,getdate()))), getdate()),120)
SET @fine = convert(varchar(16), dateadd(mi,-(datepart(mi,getdate())), getdate()),120)
SET @ades = convert(varchar(16),Getdate(),120)

PRINT @iniz + ' - ' + @fine + ' - ' + @ades