[英]SQL query to display the records which have 3 or more consecutive rows and the amount of people more than 100
我有一個具有以下結構的表:
+----+------------+--------+
| id | visit_date | people |
+----+------------+--------+
| 1 | 2017-01-01 | 10 |
| 2 | 2017-01-02 | 109 |
| 3 | 2017-01-03 | 150 |
| 4 | 2017-01-04 | 99 |
| 5 | 2017-01-05 | 145 |
| 6 | 2017-01-06 | 1455 |
| 7 | 2017-01-07 | 199 |
| 8 | 2017-01-08 | 188 |
+----+------------+--------+
我需要一個查詢來顯示連續 3 行或更多行且人數超過 100 的記錄。所以輸出將是:
+----+------------+--------+
| id | visit_date | people |
+----+------------+--------+
| 5 | 2017-01-05 | 145 |
| 6 | 2017-01-06 | 1455 |
| 7 | 2017-01-07 | 199 |
| 8 | 2017-01-08 | 88 |
+----+------------+--------+
為方便起見,創建表語句:
CREATE TABLE stadium(id INT, visit_date DATE, people INT);
INSERT INTO stadium VALUES(1, '01/JAN/17', 10);
INSERT INTO stadium VALUES(1, '02/JAN/17', 109);
INSERT INTO stadium VALUES(1, '03/JAN/17', 150);
INSERT INTO stadium VALUES(1, '04/JAN/17', 99);
INSERT INTO stadium VALUES(1, '05/JAN/17', 145);
INSERT INTO stadium VALUES(1, '06/JAN/17', 1455);
INSERT INTO stadium VALUES(1, '07/JAN/17', 199);
INSERT INTO stadium VALUES(1, '08/JAN/17', 188);
這是在 Oracle SQL 中
如果有人可以解釋邏輯和解決方案,我將非常感激。
這是一種間隙和島嶼問題。 您可以使用行號的差異來識別組。 然后使用count(*)
來計算行數和過濾器:
select s.*
from (select s.*,
count(*) over (partition by id, seqnum - seqnum_2) as num_in_row
from (select s.*,
row_number() over (partition by id order by visit_date) as seqnum,
row_number() over (partition by id, (case when people > 100 then 1 else 0 end) order by visit_date) as seqnum_2
from stadium s
) s
where people > 100
) s
where num_in_row >= 3;
這是 SQL 小提琴。
這是一個典型的模式匹配問題。 match_recognize
可以快速完成此類任務。
select id, visit_date, people
from stadium
match_recognize(
order by visit_date
all rows per match
pattern ( a{3, } )
define a as people >= 100 -- or > 100?
);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.