Simultaneous calls

后端 未结 2 571
-上瘾入骨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: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+.

提交回复
热议问题