Reputation: 185
I'm having the toughest time trying to solve this issue at work. I don't even know how to ask the question to be honest. I want to get the peak counts of calls that occurred during the same time.
I tried by breaking down the date range into minutes (resulting in a huge data set) and getting a count of calls that occurred during these times but the counts were off (I was off by a factor of 10) since I know the total calls.
1 | 2012-01-01 01:15:00.000 | 2012-01-01 01:16:00.000
2 | 2012-01-01 01:14:00.000 | 2012-01-01 01:17:00.000
3 | 2012-01-01 01:18:00.000 | 2012-01-01 01:20:00.000
The during the first calls datetime range, 2 calls happened (itself and number 2). Same with 2. Call 3 no calls happened during that datetime range. This is pretty simplified since we're talking about datetime ranges throughout the day that may range many minutes or only a few seconds. I need to find the peak per month. So for this example, January would have a peak of 2 (I don't need to know the date range that decided the number)
Upvotes: 0
Views: 145
Reputation: 1269563
This is my preferred way. It starts with a list of all the times when calls start or stop, and then calculates the number of simultaneous calls:
with t as (
select starttime as thetime, 1 as isstart, 0 as isend
from calls
union all
select endtime, 0 as isstart, 1 as issend
from calls
),
t2 as (
select thetime, row_number() over (order by thetime) as numcalls,
isstart, isend,
row_number() over (partition by isstart order by thetime) as cumstartsorends
from t
),
t3 as (
select thetime,
(case when isstart = 1 then cumstartsorends
else numcalls - cumstartsorends
end) as numstarts,
(case when isend = 1 then cumstartsorends
else numcalls - cumstartsorends
end) as numends
from t2
)
select year(thetime) as yr, month(thetime) as mon,
max(numstarts - numends) as maxcum
from t3
group by year(thetime), month(thetime)
What this query really wants to do is a cumulative sum on each time (start time or end time. However, that is not supported until 2012.
So, it does a trick. It calculates the cumulative number of starts and stops. However, these are only on the start time or end time record. To get the other value, it also calculates the total starts and stops, and subtracts this value. So, each time stamp has the cumulative number of starts and stops. The difference is the number of concurrent calls.
Upvotes: 1