目录
- [1 题目](#1 题目)
- [2 建表语句](#2 建表语句)
- [3 题解](#3 题解)
1 题目
2 建表语句
sql
CREATE TABLE IF NOT EXISTS user_login_tb (
uid INT,
login_date DATE
);
insert into user_login_tb(uid, login_date) values
( 1, '2022-08-02')
,(1, '2022-08-03')
,(2, '2022-08-03')
,(2, '2022-08-04')
,(2, '2022-08-05')
,(2, '2022-08-05')
,(3, '2022-08-05')
,(2, '2022-08-06')
,(4, '2022-08-06')
,(4, '2022-08-07');
3 题解
sql
WITH t AS (SELECT uid,
login_date,
ROW_NUMBER() OVER (PARTITION BY uid ORDER BY login_date) AS rn
FROM user_login_tb
group by uid, login_date -- 一个用户一天可能多次登录
)
SELECT part AS days_range,
COUNT(DISTINCT uid) AS user_num
FROM (SELECT uid,
dd,
COUNT(*) AS cnd,
CASE
WHEN COUNT(*) < 2 THEN '未连续登录'
WHEN COUNT(*) < 4 THEN '连续登录2~3天'
WHEN COUNT(*) < 8 THEN '连续登录4~7天'
ELSE '连续登录大于7天'
END AS part
FROM (SELECT *,
DATE_SUB(login_date, rn) AS dd
FROM t) t1
GROUP BY uid, dd) t2
GROUP BY part
-- 记住sql的执行顺序
-- FROM -> JOIN -> ON -> WHERE -> GROUP BY -> HAVING -> SELECT -> DISTINCT -> ORDER BY -> LIMIT
ORDER BY user_num DESC;
执行结果