LeetCode MySQL 601. 体育馆的人流量(row_number+over+cast)

文章目录

1. 题目

X 市建了一个新的体育馆,每日人流量信息被记录在这三列信息中:序号 (id)、日期 (visit_date)、 人流量 (people)。

请编写一个查询语句,找出人流量的高峰期。高峰期时,至少连续三行记录中的人流量不少于100。

例如,表 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-08 | 188       |
+------+------------+-----------+

对于上面的示例数据,输出为:

+------+------------+-----------+
| id   | visit_date | people    |
+------+------------+-----------+
| 5    | 2017-01-05 | 145       |
| 6    | 2017-01-06 | 1455      |
| 7    | 2017-01-07 | 199       |
| 8    | 2017-01-08 | 188       |
+------+------------+-----------+

提示:
每天只有一行记录,日期随着 id 的增加而增加。

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/human-traffic-of-stadium
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

2. 解题

  • 使用 id 跟排序行号做差,连续的做差是一样的
select stadium.*, id - cast(row_number() over(partition by people >= 100) as signed) rnk 
from stadium
where people >= 100
{"headers": ["id", "visit_date", "people", "rnk"], 
"values": [
[2, "2017-01-02", 109, 1], 
[3, "2017-01-03", 150, 1], 
[5, "2017-01-05", 145, 2], 
[6, "2017-01-06", 1455, 2], 
[7, "2017-01-07", 199, 2], 
[8, "2017-01-08", 188, 2]]}
  • 再套一层,算出 rnk 一样的有多少个
select id, visit_date, people,
        count(*) over(partition by rnk) cnt

from
(
    select stadium.*, 
            id - cast(row_number() over(partition by people >= 100) as signed) rnk
    from stadium
    where people >= 100
) t
{"headers": ["id", "visit_date", "people", "cnt"], 
"values": [
[2, "2017-01-02", 109, 2], 
[3, "2017-01-03", 150, 2], 
[5, "2017-01-05", 145, 4], 
[6, "2017-01-06", 1455, 4], 
[7, "2017-01-07", 199, 4], 
[8, "2017-01-08", 188, 4]]}
  • 最后筛选 cnt >= 3 的
# Write your MySQL query statement below
select id, visit_date, people
from
(
    select id, visit_date, people,
            count(*) over(partition by rnk) cnt
    from
    (
        select stadium.*, 
                id - cast(row_number() over(partition by people >= 100) as signed) rnk
        from stadium
        where people >= 100
    ) t
) t
where cnt >= 3

或者 3表连接

# Write your MySQL query statement below
select distinct a.*
from stadium a, stadium b, stadium c
where 
    (
        (b.id = a.id+1 and c.id = b.id+1) or
        (c.id = b.id+1 and a.id = c.id+1) or
        (a.id = c.id+1 and b.id = a.id+1)
    )
    and a.people>=100 
    and b.people>=100 
    and c.people>=100
order by a.id

我的CSDN博客地址 https://michael.blog.csdn.net/

长按或扫码关注我的公众号(Michael阿明),一起加油、一起学习进步!
Michael阿明

猜你喜欢

转载自blog.csdn.net/qq_21201267/article/details/107737090