我试图通过查看日期时间范围来计算进行特定呼叫时同时呼叫的数量。我的查询有效,但只需要大约 10 分钟才能执行 95,000 条记录,这太长了。有什么优化的想法吗?
SELECT r.*,
rr.ChannelsActive 'ChannelsActive'
FROM #rg r
OUTER APPLY
(
SELECT SUM(1) AS ChannelsActive
FROM #rg r_inner
WHERE
(
r_inner.CallStart BETWEEN r.CallStart AND r.CallEnd
OR r_inner.CallEnd BETWEEN r.CallStart AND r.CallEnd
OR r.CallStart BETWEEN r_inner.CallStart AND r_inner.CallEnd
OR r.CallEnd BETWEEN r_inner.CallStart AND r_inner.CallEnd
)
) rr
示例数据
CREATE TABLE #rg
(
CallStart DATETIME,
CallEnd DATETIME
)
CREATE INDEX ix1
ON #rg(CallStart, CallEnd)
CREATE INDEX ix2
ON #rg(CallEnd, CallStart);
WITH T(N, R)
AS (SELECT TOP (95000) ROW_NUMBER() OVER (ORDER BY (SELECT 0)) AS RN,
ABS(120 + 30 * SQRT(-2 * LOG(ABS(CAST(CAST(CRYPT_GEN_RANDOM(8) AS BIGINT) AS FLOAT) / 9223372036854775807))) * COS(2 * PI() * ABS(CAST(CAST(CRYPT_GEN_RANDOM(8) AS BIGINT) AS FLOAT) / 9223372036854775807)))
FROM sys.all_objects o1,
sys.all_objects o2)
INSERT INTO #rg
SELECT DATEADD(SECOND, N, GETDATE()),
DATEADD(SECOND, N + R, GETDATE())
FROM T