SQL架构
表:Stadium
+---------------+---------------------+
| Column Name | Type |
+---------------+---------------------+
| id | int |
| visit_date | date |
| people | int |
+---------------+---------------------+
visit_date 是表的主键
每日人流量信息被记录在这三列信息中:序号 (id)、日期 (visit_date)、 人流量 (people)
每天只有一行记录,日期随着 id 的增加而增加
编写一个 SQL 查询以找出每行的人数大于或等于 100 且 id 连续的三行或更多行记录。
返回按 visit_date 升序排列 的结果表。
查询结果格式如下所示。
示例 1:
输入:
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 连续的记录。
通过次数38,515
解题思路
关键:id前中后三个连续且大于等于100。
分成3种解题思路:
根据id连续分三种情况再查看people情况,可以查看代码1和4
根据people大于99分区,然后再查看id连续情况,可以查看代码3
根据id连续分区,在统计分区内>=100个数是否满足条件,可以查看代码2
代码1
select id, visit_date, people
from
( select id, visit_date, people,
lead(people, 1) over(order by id) as lead1,
lead(people, 2) over(order by id) as lead2,
lag(people, 1) over(order by id) as lag1,
lag(people, 2) over(order by id) as lag2
from Stadium) as t
where (people >= 100 and lead1 >= 100 and lag1 >= 100) or
(people >= 100 and lead1 >=100 and lead2>=100) or
(people >= 100 and lag1 >=100 and lag2 >= 100)
代码2
select id, visit_date, people
from (
select id, visit_date, people, count(*) over(partition by tag) as ktag
from (
select *, id - row_number() over(order by id) as tag
from stadium
where people >= 100) as t) as y
where ktag>=3
代码3
select distinct s.*
from stadium s,
(select id,
visit_date,
people,
(@cnt:=IF(people>99,@cnt+1,0)) as cnt
from stadium,(select @cnt:=0) b) c
where c.cnt>2 and s.id between c.id-c.cnt+1 and c.id
代码4
select distinct id, visit_date , people
from (
select a.*
from stadium a, stadium b,stadium c
where (a.id = b.id - 1 and b.id = c.id - 1 and
a.people >= 100 and b.people >= 100 and c.people >= 100)
union all
select b.*
from stadium a, stadium b,stadium c
where (b.id = a.id + 1 and b.id = c.id - 1 and
a.people >= 100 and b.people >= 100 and c.people >= 100)
union all
select a.*
from stadium a, stadium b,stadium c
where (a.id = b.id + 1 and b.id = c.id + 1 and
a.people >= 100 and b.people >= 100 and c.people >= 100)) as t
order by visit_date
作者:eill123
链接:https://leetcode-cn.com/problems/human-traffic-of-stadium/solution/601-ti-yu-guan-de-ren-liu-liang-by-eill1-wrcm/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。