首頁 > 軟體

MySQL如何計算連續登入天數

2022-05-13 21:50:53

建表、insert資料

create table tmp_login (
  user_id int(11) ,
  login_date datetime
);
insert into tmp_login values(2,'2020-05-29 11:12:12');
insert into tmp_login values(2,'2020-05-29 15:12:12');
insert into tmp_login values(2,'2020-05-30 11:12:12');
insert into tmp_login values(2,'2020-05-31 11:12:12');
insert into tmp_login values(2,'2020-06-01 11:12:12');
insert into tmp_login values(2,'2020-06-02 11:12:12');
insert into tmp_login values(2,'2020-06-03 11:12:12');
insert into tmp_login values(2,'2020-06-04 11:12:12');
insert into tmp_login values(2,'2020-06-05 11:12:12');
insert into tmp_login values(2,'2020-06-06 11:12:12');
insert into tmp_login values(2,'2020-06-07 11:12:12');
insert into tmp_login values(7,'2020-06-01 11:12:12');
insert into tmp_login values(7,'2020-06-02 11:12:12');
insert into tmp_login values(7,'2020-06-03 11:12:12');
insert into tmp_login values(7,'2020-06-05 11:12:12');
insert into tmp_login values(7,'2020-06-06 11:12:12');
insert into tmp_login values(7,'2020-06-07 11:12:12');
insert into tmp_login values(7,'2020-06-08 11:12:12');

方法一 row_number()

1.查詢所有使用者的每日登入記錄

select distinct user_id, date(login_date) as days 
from tmp_login;

2.row_number()計算登入時間排序

select user_id, days, row_number() over(partition by user_id order by days) as rn
from (
	select distinct user_id, date(login_date) as days from tmp_login) t1;

3.用登入時間 - row_number(),如果得到的日期相同,則認為是連續登入日期

select *, date_sub(days, interval rn day) as  results
from(
	select user_id, days, row_number() over(partition by user_id order by days) as rn
	from (
		select distinct user_id, date(login_date) as days from tmp_login) t1
) t2;

4. 按user_id、results分組就可得出連續登入天數

select user_id, count(*) as num_days
from (
	select *, date_sub(days, interval rn day) as  results
	from(
		select user_id, days, row_number() over(partition by user_id order by days) as rn
		from (
			select distinct user_id, date(login_date) as days from tmp_login) t1
	) t2) t3
group by user_id , results;

直接用日期減去row_number(),不用date_sub的話,遇到登入日期跨月時會計算錯誤,

方法二lead() 或 lag()

這種情況適合的場景是,需要查詢連續登入超過n天的使用者,n為確定值

如果n為4,即計算連續登入超過4天的使用者

-- lead計算連續登入
select distinct user_id 
from(
	select user_id, days, datediff(lead(days, 3, '1970-01-01') over(partition by user_id order by days), days)as results
	from (
		select distinct user_id, date(login_date) as days from tmp_login) t1) t2
where results = 3;

連續登入4天,則日期差應該為3。

以上為個人經驗,希望能給大家一個參考,也希望大家多多支援it145.com。


IT145.com E-mail:sddin#qq.com