体育馆人流量

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 的增加而增加。

第一种
连续三天人流量大于100, 列出a的id在前 中间 最后 三种情况,最后去重排序

SELECT distinct a.id,a.visit_date,a.people
FROM stadium as a,stadium as b,stadium as c
where ((a.id = b.id-1 and b.id=c.id-1) or
       (a.id-1 = b.id and a.id+1 = c.id) or
       (a.id-1 = c.id and c.id-1 = b.id))
  and (a.people>=100 and b.people>=100 and c.people>=100)
order by  a.id

第二种
利用mysql 自定义变量,将连续的人流量大于100的用同一个标记标识

 select 
        t1.id,t1.visit_date,t1.people,t1.flag
 from
        (
        select id,visit_date,people,(case when people<100 then @i:=@i+1 else @i end) flag
        from stadium,(select @i:=0) as init
        )t1
 where 
        t1.people>=100

上述SQL 结果如下
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”

然后根据flag 分组count,匹配count数大于2 的记录即可

完整SQL如下

select 
    t3.id,t3.visit_date,t3.people
from
    (
    select 
        t1.flag f1,count(t1.flag) cn
    from
        (
        select id,visit_date,people,(case when people<100 then @i:=@i+1 else @i end) flag
        from stadium,(select @i:=0) as init
        )t1
    where 
        t1.people>=100
    group by 
        t1.flag
    )t2
join
    (
    select id,visit_date,people,(case when people<100 then @a:=@a+1 else @a end) f2
    from stadium,(select @a:=0) as init
    )t3
on
    t2.cn>2 and t3.people>=100 and  t2.f1=t3.f2
order by
    t3.id

你可能感兴趣的:(力扣,SQL,体育馆人流量,SQL,力扣)