一、准备工作
Create table If Not Exists Stadium (id int, visit_date DATE NULL, people int);
Truncate table Stadium;
insert into Stadium (id, visit_date, people) values ('1', '2017-01-01', '10');
insert into Stadium (id, visit_date, people) values ('2', '2017-01-02', '109');
insert into Stadium (id, visit_date, people) values ('3', '2017-01-03', '150');
insert into Stadium (id, visit_date, people) values ('4', '2017-01-04', '99');
insert into Stadium (id, visit_date, people) values ('5', '2017-01-05', '145');
insert into Stadium (id, visit_date, people) values ('6', '2017-01-06', '1455');
insert into Stadium (id, visit_date, people) values ('7', '2017-01-07', '199');
insert into Stadium (id, visit_date, people) values ('8', '2017-01-09', '188');
# 编写解决方案找出每行的人数大于或等于 100 且 id 连续的三行或更多行记录。
# 返回按 visit_date 升序排列 的结果表。
输入:
输出:
二、分析
三、实现
with t as (
select * from stadium where people >=100 -- 每行人数大于等于100
), t1 as (
select
*,
row_number() over (order by id) rn -- 对大于等于100的id排序
from t
), t2 as (
select
*,
id-rn as 差值 -- 对id和排序求差,差值相等的为连续
from t1
),t3 as (
select 差值,count(差值) cn from t2 group by 差值 -- 求差值相等且大于等于3的记录
)
select id,visit_date,people from t2 ,t3 where t2.差值=t3.差值 and cn>=3 order by id;
四、总结
此题稍微微有一点难度,如果看不明白可以对题目进行分解分析,分析出一步之后再接下一步来查询,题目已经要求人数大于等于100且id连续三行,就可以先筛选出大于等于100 的id 然后排序求差 差值相等的均为id连续的 ,最后筛选差值总数大于等于3 的,便出来了最后结果;