I have a table containing Call records:
tbl_calls
cl_Id
cl_StartDate
cl_endDate
I am passing two parameters @StartDate
and @EndDate
to my stored procedure.
My requirement is to get the count of Call Records between every 15 minutes of duration.
For example, if:
@StartDate = '2015-11-16 00:00:00.000',
@EndDate = '2015-11-16 23:59:00.000'
Output should be:
Date Count
2015-11-16 00:00:00.000 10(Count of startDate between '2015-11-16 00:00:00.000' AND '2015-11-16 00:15:00.000')
2015-11-16 00:15:00.000 7(Count of startDate between '2015-11-16 00:15:00.000' AND '2015-11-16 00:30:00.000')
2015-11-16 00:30:00.000 50(Count of startDate between '2015-11-16 00:30:00.000' AND '2015-11-16 00:45:00.000')
upto @EndDate
I've tried the following query, however it doesn't work properly. Is there a better way to do this?
DECLARE @StartDate DATETIME = DATEADD(DAY,-1,GETUTCDATE()),
@EndDate DATETIME = GETUTCDATE()
SELECT New
FROM
(SELECT
(CASE
WHEN cl_StartTime BETWEEN @StartDate AND
DATEADD(MINUTE, 15, @StartDate)
THEN 1
ELSE 0
END) AS New
FROM
tbl_Calls WITH (NOLOCK)
WHERE
cl_StartTime BETWEEN @StartDate AND @EndDate) AS Inners
GROUP BY
New
Let me know if you need further details.
Best Answer
This is a classic example of how a "Numbers table" can really help get the results you need.
Essentially, you create a table containing the 15 minute increments you desire, then join your table to obtain an aggregate number of calls for each 15 minute increment.
In example, I'm using temporary tables for both tables. You'd likely want to make the
#Intervals
table permanent.Create the testbed, and populate some sample data:
Show the rows in both tables:
Join both tables to get the aggregate count of Calls between the 15 minute date ranges:
On my test platform, I get the following results from the three
select
statements:Looking at your comment on @Thofle's answer, it looks like you want to see all time intervals, even if there were no calls during the given interval. To accomplish that, you can simply modify the
select
query to use aLEFT JOIN
, andCOUNT(...)
the number ofCalls
rows, like: