感谢出题者,如有冒犯,请与我联系,希望和大家一起学习交流。(目前使用oracle数据库环境编写sql)
题目
有一个商场,每日人流量信息被记录在这三列信息中:序号 (id)、日期 (date)、 人流量 (people)。请编写一个查询语句,找出高峰期时段,要求连续三天及以上,并且每天人流量均不少于100。例如,表 stadium:
对于上面的示例数据,输出为:
该如何写这个SQL?
读者可以试着自己思考写下,再往下翻... 如有不同解题方式,大家一起交流。
ID这边当作是连续有序值,如果 实际环境中不是的,以下sql需要再嵌一层,列出有序列代替ID:
sys@WIL> WITH T AS 2 (SELECT 1 ID, DATE '2019-01-01' DT, 10 PEOPLE 3 FROM DUAL 4 UNION ALL 5 SELECT 2 ID, DATE '2019-01-02' DT, 109 PEOPLE 6 FROM DUAL 7 UNION ALL 8 SELECT 3 ID, DATE '2019-01-03' DT, 150 PEOPLE 9 FROM DUAL 10 UNION ALL 11 SELECT 4 ID, DATE '2019-01-04' DT, 99 PEOPLE 12 FROM DUAL 13 UNION ALL 14 SELECT 5 ID, DATE '2019-01-05' DT, 145 PEOPLE 15 FROM DUAL 16 UNION ALL 17 SELECT 6 ID, DATE '2019-01-06' DT, 1455 PEOPLE 18 FROM DUAL 19 UNION ALL 20 SELECT 7 ID, DATE '2019-01-07' DT, 199 PEOPLE 21 FROM DUAL 22 UNION ALL 23 SELECT 8 ID, DATE '2019-01-08' DT, 188 PEOPLE 24 FROM DUAL) 25 SELECT ID, DT, PEOPLE 26 FROM (SELECT TT.*, COUNT(*) OVER(PARTITION BY GID) CN 27 FROM (SELECT T.*, ID - ROW_NUMBER() OVER(ORDER BY DT) GID 28 FROM T 29 WHERE PEOPLE > 100) TT) 30 WHERE CN >= 3 31 ORDER BY 2; ID DT PEOPLE ---------- ---------- ---------- 5 2019-01-05 145 6 2019-01-06 1455 7 2019-01-07 199 8 2019-01-08 188