题目:获取连续三天登陆的用户
表结构:
CREATE TABLE `temp_last_3_day`
(
uid varchar(25) DEFAULT NULL comment '用户id',
dt date DEFAULT NULL comment '日期'
) ENGINE = InnoDB
AUTO_INCREMENT = 8
DEFAULT CHARSET = utf8mb4;
表数据:
INSERT INTO temp_last_3_day (`uid`, `dt`)
VALUES ('123', '2021-08-02');
INSERT INTO temp_last_3_day (`uid`, `dt`)
VALUES ('123', '2021-08-03');
INSERT INTO temp_last_3_day (`uid`, `dt`)
VALUES ('123', '2021-08-04');
INSERT INTO temp_last_3_day (`uid`, `dt`)
VALUES ('456', '2021-11-02');
INSERT INTO temp_last_3_day (`uid`, `dt`)
VALUES ('456', '2021-12-09');
INSERT INTO temp_last_3_day (`uid`, `dt`)
VALUES ('789', '2021-01-01');
INSERT INTO temp_last_3_day (`uid`, `dt`)
VALUES ('789', '2021-04-23');
INSERT INTO temp_last_3_day (`uid`, `dt`)
VALUES ('789', '2021-09-10');
INSERT INTO temp_last_3_day (`uid`, `dt`)
VALUES ('789', '2021-09-12');
数据预览:
解题思路
对数据进行窗口的排序,用row_number()函数,用日期减排序,如果日期是+1递增的,排序也是+1递增的,减之后的结果应该相同
1,对数据进行窗口排序
2,用函数datesub对日期相减
3,group by uid 求出日期相同的条数大于3的即为结果