cihadakt
cihadakt

Reputation: 3214

Date range advanced count calculation in TSQL

I am working on call center project and I have to calculate the call arrivals at the same time between specific time ranges. I have to write a procedure which has parameters StartTime, EndTime and Interval

For Example:

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

so program should divide the 1-hour time range into 3 parts and each part should count the arrivals which started and finished in this range OR arrivals which started and haven't finished yet

Should be like this:

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

Any suggestions how to calculate them?

Upvotes: 0

Views: 516

Answers (2)

Marco Jaquilano
Marco Jaquilano

Reputation: 11

Look for 1 hour ago range:

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

Upvotes: 1

Tim Schmelter
Tim Schmelter

Reputation: 460288

You can use DATEADD to GROUP BY your timespan:

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 

Sample data:

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));

Here's a fiddle: http://sqlfiddle.com/#!3/ee6f9/1/0

Upvotes: 2

Related Questions