mysql leetcode 1454. 活躍用戶 連續問題, 連續出現n次


題目:

 

 

 

從題目可知:
求活躍用戶 ———— 至少連續登錄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改成你要你次數


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM