題目:
從題目可知:
求活躍用戶 ———— 至少連續登錄5天的人 ———— 連續區間且長度大於等於5
使用方法:
自定義變量求次數,初始次數為0,當符合條件時,次數加1
邏輯條件:
id相同,前后一行時間間隔為1天【date_sub()函數】
根據以上可以得出
select id, @cnt:=if(@id=id and @pre_date=date_sub(login_date, interval 1 day), @cnt+1, 1) as cnt, @id:=id, @pre_date:=login_date from (select * from `Logins` order by id, login_date) as a (select @id:=null, @pre_date:=null, @cnt:=0) as b
注意!!!有坑
由題目或者一般情況下,用戶一天內登錄次數可能不止一次,所以會有同用戶同時間多次的登錄記錄存在
所以得去重
select id, @cnt:=if(@id=id and @pre_date=date_sub(login_date, interval 1 day), @cnt+1, 1) as cnt, @id:=id, @pre_date:=login_date from (select * from `Logins` group by id, login_date order by id, login_date) as a (select @id:=null, @pre_date:=null, @cnt:=0) as b
以上是第一步
第二步與用戶信息表連接,以次數超過5為條件,使用distinct去重
根據題目要求,還需要排序
select distinct a1.id, a1.name from `Accounts` as a1 inner join ( select id, @cnt:=if(@id=id and @pre_date=date_sub(login_date, interval 1 day), @cnt+1, 1) as cnt, @id:=id, @pre_date:=login_date from (select * from `Logins` group by id, login_date order by id, login_date) as a, (select @id:=null, @pre_date:=null, @cnt:=0) as b ) as b1 on a1.id = b1.id where b1.cnt >= 5 order by a1.id
求n次,那就將5改成你要你次數