我正在尝试从我们的数据库中查找SIP线路上的最大呼叫数。这是数据示例:
ID StartTime EndTime
66 01/03/2018 5:31:18 01/03/2018 5:31:51
66 01/03/2018 5:31:51 01/03/2018 5:32:19
66 01/03/2018 5:32:21 01/03/2018 5:34:10
66 01/03/2018 5:32:31 01/03/2018 5:33:42
66 01/03/2018 5:33:02 01/03/2018 5:33:42
66 01/03/2018 5:33:23 01/03/2018 5:34:10
66 01/03/2018 5:33:45 01/03/2018 5:34:38
66 01/03/2018 5:34:08 01/03/2018 5:34:38
从视觉上看,我的计算方法应该是5。
到目前为止,我所得出的最接近值在该示例中返回了4,并且在其他测试中也处于关闭状态。我测试过的其他代码异常繁琐(100秒)。
DECLARE @ReportStartDate datetime, @ReportEndDate datetime,
@ReportStartTime time, @ReportEndTime time
SET @ReportStartDate='1/3/2018'
SET @ReportEndDate='1/3/2018'
SET @ReportStartTime='05:00:00'
SET @ReportEndTime='06:00:00'
SET @ReportStartDate = (SELECT @ReportStartDate + @ReportStartTime)
SET @ReportEndDate = (SELECT @ReportEndDate + @ReportEndTime);
WITH C1 AS
(
SELECT startdate AS ts, +1 AS TYPE,
ROW_NUMBER() OVER(ORDER BY startdate) AS start_ordinal
FROM table
WHERE startdate >= @ReportStartDate and startdate <= @ReportEndDate
and Service_id=66 --hardcoded for testing
UNION ALL
SELECT enddate, -1, NULL
FROM table
WHERE enddate >= @ReportStartDate and enddate <=
@ReportEndDate
and Service_id=66 -- hardcoded for testing
),
C2 AS
(
SELECT *,
ROW_NUMBER() OVER( ORDER BY ts, TYPE) AS start_or_end_ordinal
FROM C1
)
SELECT MAX(2 * start_ordinal - start_or_end_ordinal) AS mx
FROM C2
WHERE TYPE = 1
答案 0 :(得分:0)
我将此逻辑写为:
with tt as (
select id, stime as thetime, 1 as inc from t union all
select id, etime, -1 as inc from t
)
select top (1) tt.*
from (select tt.*, sum(inc) over (partition by id order by thetime) as overlaps
from tt
) tt
order by overlaps desc;
对于您的示例,这也会返回“ 4”,但这对我来说很有意义。
您可以在this db<>fiddle上进行测试。