I\'m trying to calculate the number of simultaneous calls at the time a particular call is made by looking at the datetime ranges. My query works, but takes ~10 minutes to p
Use SQL like this to get a list of start/end events...
Select CallStart, 1 As CallCount From #rg
Union All
Select CallEnd, -1 From #rg
Order By CallStart
...then treat this as a simple running totals problem, which is solved differently depending upon your SQL Server version or can be easily addressed in code if that's an option.
This should do it:
;WITH cteCallEvents As
(
SELECT *, CallStart As EventTime, 1 As EventType FROM #rg r
UNION ALL
SELECT *, CallEnd As EventTime, 0 As EventType FROM #rg r
)
, cteCallCounts As
(
SELECT *,
ROW_NUMBER() OVER(Order By EventTime) as EventCount,
ROW_NUMBER() OVER(Partition By EventType Order By EventTime) as TypeCount
FROM cteCallEvents
)
SELECT *,
2*TypeCount - EventCount As OpenCalls
FROM cteCallCounts
WHERE EventType = 1
It should take a couple of seconds at most. Should work on any SQL Server 2005+.