Hive-SQL查詢連續活躍登錄用戶思路詳解
連續活躍登陸的用戶指至少連續2天都活躍登錄的用戶
解決類似場景的問題
創建數據
CREATE TABLE test5active( dt string, user_id string, age int) ROW format delimited fields terminated BY ','; INSERT INTO TABLE test5active VALUES ('2019-02-11','user_1',23),('2019-02-11','user_2',19), ('2019-02-11','user_3',39),('2019-02-11','user_1',23), ('2019-02-11','user_3',39),('2019-02-11','user_1',23), ('2019-02-12','user_2',19),('2019-02-13','user_1',23), ('2019-02-15','user_2',19),('2019-02-16','user_2',19);
思路一:
1、因為每天用戶登錄次數可能不止一次,所以需要先將用戶每天的登錄日期去重。
2、再用row_number() over(partition by _ order by _)函數將用戶id分組,按照登陸時間進行排序。
3、計算登錄日期減去第二步驟得到的結果值,用戶連續登陸情況下,每次相減的結果都相同。
4、按照id和日期分組並求和,篩選大於等於2的即為連續活躍登陸的用戶。
第一步:用戶登錄日期去重
select DISTINCT dt,user_id from test5active;
第二步:用row_number() over()函數計數
select t1.user_id,t1.dt, row_number() over(partition by t1.user_id order by t1.dt) day_rank from ( select DISTINCT dt,user_id from test5active )t1;
第三步:日期減去計數值得到結果
select t2.user_id,t2.dt,date_sub(t2.dt,t2.day_rank) as dis from ( select t1.user_id,t1.dt, row_number() over(partition by t1.user_id order by t1.dt) day_rank from ( select DISTINCT dt,user_id from test5active )t1)t2;
第四步:根據id和結果分組並計算總和,大於等於2的即為連續登陸的用戶,得到 用戶id,開始日期,結束日期,連續登錄天數
select t3.user_id,min(t3.dt),max(t3.dt),count(1) from ( select t2.user_id,t2.dt,date_sub(t2.dt,t2.day_rank) as dis from ( select t1.user_id,t1.dt, row_number() over(partition by t1.user_id order by t1.dt) day_rank from ( select DISTINCT dt,user_id from test5active )t1 )t2 )t3 group by t3.user_id,t3.dis having count(1)>1;
用戶id 開始日期 結束日期 連續登錄天數
最後:連續登陸的用戶
select distinct t4.user_id from ( select t3.user_id,min(t3.dt),max(t3.dt),count(1) from ( select t2.user_id,t2.dt,date_sub(t2.dt,t2.day_rank) as dis from ( select t1.user_id,t1.dt, row_number() over(partition by t1.user_id order by t1.dt) day_rank from ( select DISTINCT dt,user_id from test5active )t1 )t2 )t3 group by t3.user_id,t3.dis having count(1)>1 )t4;
思路二:使用lag(向後)或者lead(向前)
select user_id,t1.dt, lead(t1.dt) over(partition by user_id order by t1.dt) as last_date_id from ( select DISTINCT dt,user_id from test5active )t1;
select distinct t2.user_id from ( select user_id,t1.dt, lead(t1.dt) over(partition by user_id order by t1.dt) as last_date_id from ( select DISTINCT dt,user_id from test5active )t1 )t2 where datediff(last_date_id,t2.dt)=1;
參考:2020年大廠面試題-數據倉庫篇
SQL 查詢連續登陸7天以上的用戶
到此這篇關於Hive-SQL查詢連續活躍登陸的用戶的文章就介紹到這瞭,更多相關SQL查詢連續登陸的用戶內容請搜索WalkonNet以前的文章或繼續瀏覽下面的相關文章希望大傢以後多多支持WalkonNet!