>> 建表
create table user_login(
user_id int,
login_time datetime,
)
>> 数据插入
insert into user_login values (1,'2022-06-01 11:00:00.000');
insert into user_login values (1,'2022-06-01 12:00:00.000');
insert into user_login values (1,'2022-06-01 12:00:00.000');
insert into user_login values (1,'2022-06-02 11:00:00.000');
insert into user_login values (1,'2022-06-03 11:00:00.000');
insert into user_login values (2,'2022-06-01 11:00:00.000');
insert into user_login values (2,'2022-06-02 11:00:00.000');
insert into user_login values (2,'2022-06-04 11:00:00.000');
insert into user_login values (3,'2022-06-01 11:00:00.000');
insert into user_login values (3,'2022-06-02 11:00:00.000');
insert into user_login values (3,'2022-06-04 11:00:00.000');
insert into user_login values (3,'2022-06-05 11:00:00.000');
insert into user_login values (3,'2022-06-06 11:00:00.000');
insert into user_login values (3,'2022-06-07 11:00:00.000');
insert into user_login values (3,'2022-06-08 11:00:00.000');
>> 答案及解题思路
1.通过开窗函数对日期进行每个用户的登录日期排序
2.将登录日期和排序序号相减得到相同连续日期
3.按照得到的相同连续日期分组,count大于3的为连续登录超过3天的。
select
B.user_id
from
(
select
A.user_id,
A.login_date,
datediff (day,A.login_date,A.rn) AS inteval_days
from
(
select
user_id,
CONVERT(varchar(100), login_time, 23) login_date,
row_number() over (partition by user_id order by CONVERT(varchar(100), login_time, 23)) as rn
from
user_login
)A
)B
group by B.user_id,B.inteval_days
having count(1) >= 3;