Simultaneous calls

后端 未结 2 555
-上瘾入骨i
-上瘾入骨i 2021-01-18 05:07

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

相关标签:
2条回答
  • 2021-01-18 05:31

    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.

    0 讨论(0)
  • 2021-01-18 05:35

    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+.

    0 讨论(0)
提交回复
热议问题