查詢7天連續登陸用戶這個問題很經典,解決方法也有很多,這里我講一下筆者的方法,希望對大家有幫助。
具體思路:
1、因為每天用戶登錄次數可能不止一次,所以需要先將用戶每天的登錄日期去重。
2、再用row_number() over(partition by _ order by _)函數將用戶id分組,按照登陸時間進行排序。
3、計算登錄日期減去第二步驟得到的結果值,用戶連續登陸情況下,每次相減的結果都相同。
4、按照id和日期分組并求和,篩選大于等于7的即為連續7天登陸的用戶。
表信息如下圖
第一步:用戶登錄日期去重
1
|
select distinct date ( date ) as 日期,id from orde; |
結果為:
第二步:用row_number() over()函數計數
1
|
select *,row_number() over(partition by id order by 日期) as cum from ( select distinct date ( date ) as 日期,id from orde)a; |
結果為:
第三步:日期減去計數值得到結果
1
|
select *, date (日期)-cum as 結果 from ( select *,row_number() over(partition by id order by 日期) as cum from ( select distinct date ( date ) as 日期,id from orde)a)b; |
結果:
第四步:根據id和結果分組并計算總和,大于等于7的即為連續登陸7天的用戶
1
|
select id, count (*) from ( select *, date (日期)-cum as 結果 from ( select *,row_number() over(partition by id order by 日期) as cum from ( select distinct date ( date ) as 日期,id from orde)a)b)c group by id,結果 having count (*)>=7; |
結果為:
用了多次嵌套查詢,最終得到我們需要的結果。
到此這篇關于sql查詢連續登陸7天以上的用戶的方法實現的文章就介紹到這了,更多相關sql查詢連續登陸用戶內容請搜索服務器之家以前的文章或繼續瀏覽下面的相關文章希望大家以后多多支持服務器之家!
原文鏈接:https://www.cnblogs.com/ikww/p/12012831.html