思路:
1、因为每天用户登录次数可能不止一次,所以需要先将用户每天的登录日期去重。
2、再用row_number() over(partition by _ order by _)函数将用户id分组,按照登录日期进行排序。
3、计算登录日期减去第二步骤得到的结果值,用户连续登录情况下,相减的结果都相同。
4、按照id和日期分组并计数,筛选大于等于3的即为连续3天登录的用户。
我用的数据库是SQL Server 2014
建表语句:
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');
查询语句
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;