描述:601. 体育馆的人流量 - 力扣(LeetCode)
编写解决方案找出每行的人数大于或等于
100
且id
连续的三行或更多行记录。返回按
visit_date
升序排列 的结果表。输入Stadium表: +------+------------+-----------+ | 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-09 | 188 | +------+------------+-----------+ 输出: +------+------------+-----------+ | id | visit_date | people | +------+------------+-----------+ | 5 | 2017-01-05 | 145 | | 6 | 2017-01-06 | 1455 | | 7 | 2017-01-07 | 199 | | 8 | 2017-01-09 | 188 | +------+------------+-----------+ 解释: id 为 5、6、7、8 的四行 id 连续,并且每行都有 >= 100 的人数记录。 请注意,即使第 7 行和第 8 行的 visit_date 不是连续的,输出也应当包含第 8 行,因为我们只需要考虑 id 连续的记录。 不输出 id 为 2 和 3 的行,因为至少需要三条 id 连续的记录。
数据准备:
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')
分析:
整体思路和之前连续问题一样,构造等差数列解决连续问题
①先对整体排名
select *,row_number() over (order by visit_date)r1 from stadium②对people大于等于100的再排个序
with t1 as ( select *,row_number() over (order by visit_date)r1 from stadium) select *,row_number() over (order by visit_date)r2 from t1 where people >= 100③对r1,r2两列做差,差值相同的即连续数列,同时用count求出连续天数
with t1 as ( select *,row_number() over (order by visit_date)r1 from stadium) , t2 as( select *,row_number() over (order by visit_date)r2 from t1 where people >= 100) select *,r1-r2 as r3,count(r1-r2) over(partition by (r1-r2))r4 from t2④筛选数据,并按照id排序
select id,visit_date,people from t3 where r4 >=3 order by id
代码:
with t1 as (
select *,row_number() over (order by visit_date)r1 from stadium)
, t2 as(
select *,row_number() over (order by visit_date)r2 from t1
where people >= 100)
, t3 as (
select *,r1-r2 as r3,count(r1-r2) over(partition by (r1-r2))r4 from t2)
select id,visit_date,people
from t3
where r4 >=3
order by id;
总结:
连续问题记得使用两个排名函数构造等差数列
本站资源均来自互联网,仅供研究学习,禁止违法使用和商用,产生法律纠纷本站概不负责!如果侵犯了您的权益请与我们联系!
转载请注明出处: 免费源码网-免费的源码资源网站 » LeetCode_sql_day16(601.体育馆的人流量)
发表评论 取消回复