2023-01-11:体育馆的人流量。编写一个 SQL 查询以找出每行的人数大于或等于 100 且

2023-01-11:体育馆的人流量。编写一个 SQL 查询以找出每行的人数大于或等于 100 且 id 连续的三行或更多行记录。返回按 visit_date 升序排列 的结果表。

DROP TABLE IF EXISTS `stadium`;
CREATE TABLE `stadium` (
  `id` int(11) NOT NULL,
  `visit_date` date NOT NULL,
  `people` int(11) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

INSERT INTO `stadium` VALUES ('1', '2017-01-01', '10');
INSERT INTO `stadium` VALUES ('2', '2017-01-02', '109');
INSERT INTO `stadium` VALUES ('3', '2017-01-03', '150');
INSERT INTO `stadium` VALUES ('4', '2017-01-04', '99');
INSERT INTO `stadium` VALUES ('5', '2017-01-05', '145');
INSERT INTO `stadium` VALUES ('6', '2017-01-06', '1455');
INSERT INTO `stadium` VALUES ('7', '2017-01-07', '199');
INSERT INTO `stadium` VALUES ('8', '2017-01-09', '188');

答案2023-01-11:

sql语句如下:


























select distinct t1.*
from stadium t1, stadium t2, stadium t3
where t1.people >= 100 and t2.people >= 100 and t3.people >= 100
and
(
      (t1.id - t2.id = 1 and t1.id - t3.id = 2 and t2.id - t3.id =1)  -- t1, t2, t3
    or
    (t2.id - t1.id = 1 and t2.id - t3.id = 2 and t1.id - t3.id =1) -- t2, t1, t3
    or
    (t3.id - t2.id = 1 and t2.id - t1.id =1 and t3.id - t1.id = 2) -- t3, t2, t1
)
order by t1.id

在这里插入图片描述

本作品采用《CC 协议》,转载必须注明作者和本文链接
微信公众号:福大大架构师每日一题。最新面试题,涉及golang,rust,mysql,redis,云原生,算法,分布式,网络,操作系统。
讨论数量: 1

尝试了一下没有开窗的写法,仅供参考

select
    tb1.*
from stadium tb1
left join
    (select
        id - sort  as seq
        ,min(visit_date) as start_date
        ,max(visit_date) as end_date
        ,count(1) as cnt
    from
        (select 
            id
            ,visit_date
            ,people
            ,@pre_people
            ,if(@pre_people != flag,@row_num := 1,@row_num :=@row_num+1) as sort
            ,@pre_people := flag
        from (
            select 
                    id,visit_date,people,if(people >= 100,'T','F') as flag
            from stadium
            ) t1,
            (select @pre_people := 'T') as t2,
            (select @row_num := 0) as t3
        ) t4 
    group by (id - sort)
    HAVING cnt >= 3  -- 可动态调整
    ) tb2 on 1=1
where tb1.visit_date >= tb2.start_date and tb1.visit_date <= tb2.end_date

file

1年前 评论

讨论应以学习和精进为目的。请勿发布不友善或者负能量的内容,与人为善,比聪明更重要!
未填写
文章
469
粉丝
21
喜欢
37
收藏
22
排名:457
访问:1.9 万
私信
所有博文
社区赞助商