统计连续登录天数超过3天的用户,输出信息包括:用户id,登录天数,起始时间,结束时间;
-- 建表
create table if not exists user_login_3days(
user_id STRING,
login_date date
);
--插入数据
insert into user_login_3days values ('01','2023-08-02');
insert into user_login_3days values ('01','2023-08-03');
insert into user_login_3days values ('01','2023-08-04');
insert into user_login_3days values ('01','2023-11-02');
insert into user_login_3days values ('01','2023-12-09');
insert into user_login_3days values ('02','2023-01-01');
insert into user_login_3days values ('02','2023-04-23');
insert into user_login_3days values ('03','2023-09-10');
insert into user_login_3days values ('03','2023-09-11');
insert into user_login_3days values ('03','2023-09-12');
insert into user_login_3days values ('04','2023-04-23');
insert into user_login_3days values ('04','2023-04-24');
insert into user_login_3days values ('05','2023-09-11');
insert into user_login_3days values ('06','2023-09-12');
-- 查询数据数据
select * from user_login_3days order by user_id;
思路1:row_number()
SELECT
t2.user_id,
count(1) as login_times,
min(t2.login_date) as start_date,
max(t2.login_date) as end_date
FROM
(
SELECT
t1.user_id,
t1.login_date,
date_sub(t1.login_date,rn) as diff_date
FROM
(
SELECT
user_id,
login_date,
row_number() over(partition by user_id order by login_date asc) as rn
FROM user_login_3days
) t1
) t2
group by t2.user_id, t2.diff_date
having login_times >= 3;
思路2:lag()/lead()
SELECT
user_id,
lag_login_date,
login_date
FROM
(SELECT
user_id,
login_date,
lag(login_date,2,login_date) over(partition by user_id order by login_date) as lag_login_date,
lead(login_date,1,login_date) over(partition by user_id order by login_date) as lead_login_date
FROM user_login_3days
) t1
where datediff(login_date,lag_login_date) =2
连续登陆问题解决的关键在于:如何判断连续?
通过对user_id分组排序后,使用登陆日期减去序号rn。如果连续,则得到的这个日期会相同。