一、题目
表:Stadium
+---------------+---------+
| Column Name | Type |
+---------------+---------+
| id | int |
| visit_date | date |
| people | int |
+---------------+---------+
visit_date 是表的主键
每日人流量信息被记录在这三列信息中:序号 (id)、日期 (visit_date)、 人流量 (people)
每天只有一行记录,日期随着 id 的增加而增加
编写一个 SQL 查询以找出每行的人数大于或等于 100 且 id 连续的三行或更多行记录。
返回按 visit_date 升序排列的结果表。
查询结果格式如下所示。
Stadium table:
+------+------------+-----------+
| 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 |
+------+------------+-----------+
Result table:
+------+------------+-----------+
| 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 连续的记录。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/human-traffic-of-stadium
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
二、解题步骤
1. 建立临时表
(1) 使用row_rank()对people大于100的id进行重新排序
(2) id - row_rank()得到rank值
Stadium table:
+------+------------+-----------+
| id | visit_date | people |row_rank rank
+------+------------+-----------+
| 1 | 2017-01-01 | 10 |
| 2 | 2017-01-02 | 109 | 1 1
| 3 | 2017-01-03 | 150 | 2 1
| 4 | 2017-01-04 | 99 |
| 5 | 2017-01-05 | 145 | 3 2
| 6 | 2017-01-06 | 1455 | 4 2
| 7 | 2017-01-07 | 199 | 5 2
| 8 | 2017-01-09 | 188 | 6 2
+------+------------+-----------+
可以看出连续的people值大于100的rank值都是相等的
#建立临时表
with t1 as(
select *,id - row_number() over(order by id) as rk
from stadium
where people >= 100
)
(3)当相同rank总数>3时,输出该rk对应的id,visit_date,people值
select id,visit_date,people
from t1
where rk in(
select rk
from t1
group by rk
having count(rk) >= 3
)
整体代码如下:
with t1 as(
select *,id - row_number() over(order by id) as rk
from stadium
where people >= 100
)
select id,visit_date,people
from t1
where rk in(
select rk
from t1
group by rk
having count(rk) >= 3
)
https://leetcode-cn.com/problems/human-traffic-of-stadium/solution/tu-jie-lian-xu-ri-qi-ji-nan-dian-fen-xi-xnj58/
2. count(*) over(partition by t_rank)
(1) 先求出rank值
(2)对rank进行分组并求总数
(3)将rank数 >=3 的数据输出
select id,visit_date,people
from(
select *,count(*) over(partition by t_rank) t2_rank
from(
select *,id-row_number()over(order by id) t_rank
from stadium
where people>99
)t
)t2
where t2.t2_rank>2
注意 rank为关键字,不能直接使用rank作为别名。