首先,我对SQL不是很熟悉。我之前在这里找到了类似的问题,但到目前为止,我无法为我的具体问题开发出一个可行的解决方案。
我有一个表格,其中包含电话记录,其中包含以下字段:
END: Holds the timestamp of when a call ended - Data Type: DATE
LINE: Holds the phone line that was used for a call - Data Type: NUMBER
CALLDURATION: Holds the duration of a call in seconds - Data Type: NUMBER
该表包含以下条目:
END LINE CALLDURATION
---------------------- ------------------- -----------------------
25/01/2012 14:05:10 6 65
25/01/2012 14:08:51 7 1142
25/01/2012 14:20:36 5 860
我需要创建一个查询,根据该表中的数据返回并发电话的数量。查询应该能够以固定间隔计算该数字,例如每5分钟计算一次。 为了更清楚,这里是一个查询应返回的示例(基于上表中的示例条目:
TIMESTAMP CURRENTLYUSEDLINES
---------------------- -------------------
25/01/2012 14:05:00 2
25/01/2012 14:10:00 1
25/01/2012 14:15:00 1
如何使用(Oracle)SQL查询执行此操作?表中目前有近100万条记录,因此查询必须尽可能快,否则执行它会花费很长时间。
答案 0 :(得分:0)
一个解决方案就是这个:
WITH t AS
(SELECT TIMESTAMP '2012-01-25 14:00:00' + LEVEL * INTERVAL '5' MINUTE AS TS
FROM dual
CONNECT BY TIMESTAMP '2012-01-25 14:00:00' + LEVEL * INTERVAL '5' MINUTE <= TIMESTAMP '2012-01-25 14:15:00'),
calls AS
(SELECT TIMESTAMP '2012-01-25 14:05:10' AS END_TIME, 6 AS LINE, 65 AS duration FROM dual
UNION ALL SELECT TIMESTAMP '2012-01-25 14:08:51', 7, 1142 FROM dual
UNION ALL SELECT TIMESTAMP '2012-01-25 14:20:36', 5, 860 FROM dual)
SELECT TS, count(distinct line)
FROM t
LEFT OUTER JOIN calls ON ts BETWEEN END_TIME - duration * INTERVAL '1' SECOND AND END_TIME
GROUP BY ts
HAVING count(distinct line) > 0
ORDER BY ts;
TS COUNT(DISTINCTLINE)
-------------------- -------------------
25.01.2012 14:05:00 2
25.01.2012 14:10:00 1
25.01.2012 14:15:00 1
3 rows selected.