练习sql语句,所有题目来自于力扣(https://leetcode.cn/problemset/database/)的免费数据库练习题。
601.体育馆的人流量
表:Stadium
| 列名 | 类型 |
|---|---|
| id | int |
| visit_date | date |
| people | int |
编写解决方案找出每行的人数大于或等于 100 且 id 连续的三行或更多行记录。
返回按 visit_date 升序排列 的结果表。
https://blog.csdn.net/dkmaa/article/details/136302362?spm=1001.2014.3001.5506
partition bywith onehund_people as (
select id,people,
case when people >=100 then 0
else people
end as peo
from Stadium
)
id - row_number() over(partition by peo order by id),得到它们的差值,至于为何这样,引用里面的文章,我已经详细说明过了,这里就不多说了。select o.id,s.visit_date,peo,s.people,o.id - row_number() over(partition by peo order by o.id) as num
from onehund_people o
left join Stadium s
on o.id = s.id
order by o.id
select num
from (
select o.id,s.visit_date,peo,s.people,o.id - row_number() over(partition by peo order by o.id) as num
from onehund_people o
left join Stadium s
on o.id = s.id
order by o.id
) as a
group by peo,num
having count(*) >=3
select id,visit_date,people
from (
select o.id,s.visit_date,peo,s.people,o.id - row_number() over(partition by peo order by o.id) as num
from onehund_people o
left join Stadium s
on o.id = s.id
order by o.id
) b
where num in
(select num
from (
select o.id,s.visit_date,peo,s.people,o.id - row_number() over(partition by peo order by o.id) as num
from onehund_people o
left join Stadium s
on o.id = s.id
order by o.id
) as a
group by peo,num
having count(*) >=3
)
and peo = 0
with onehund_people as (
select id,people,
case when people >=100 then 0
else people
end as peo
from Stadium
)
select id,visit_date,people
from (
select o.id,s.visit_date,peo,s.people,o.id - row_number() over(partition by peo order by o.id) as num
from onehund_people o
left join Stadium s
on o.id = s.id
order by o.id
) b
where num in
(select num
from (
select o.id,s.visit_date,peo,s.people,o.id - row_number() over(partition by peo order by o.id) as num
from onehund_people o
left join Stadium s
on o.id = s.id
order by o.id
) as a
group by peo,num
having count(*) >=3
)
and peo = 0

能运行就行。