SQL查詢語句求出用戶的連續(xù)登陸天數(shù)
一、題目描述
求解用戶登陸信息表中,每個用戶連續(xù)登陸平臺的天數(shù),連續(xù)登陸基礎(chǔ)為匯總?cè)掌诒仨毜顷?,表中每天只有一條用戶登陸數(shù)據(jù)(計算中不涉及天內(nèi)去重)。
表描述:user_id:用戶的id;
sigin_date:用戶的登陸日期。
二、解法分析
注:求解過程有多種方式,下述求解解法為筆者思路,其他解法可在評論區(qū)交流。
思路:
該問題的突破的在于登陸時間,計算得到連續(xù)登陸標(biāo)識,以標(biāo)識分組為過濾條件,得到連續(xù)登陸的天數(shù),最后以user_id分組,以count()函數(shù)求和得到每個用戶的連續(xù)登陸天數(shù)。
連續(xù)登陸標(biāo)識 =(當(dāng)日登陸日期 - 用戶的登陸日期)- 開窗排序的順序號(倒序)
三、求解過程及結(jié)果展示
1.數(shù)據(jù)準(zhǔn)備
-- 1.建表語句 drop table if exists test_sigindate_cnt; create table test_sigindate_cnt( user_id string ,sigin_date string ) ; -- 2.測試數(shù)據(jù)插入語句 insert overwrite table test_sigindate_cnt select 'uid_1' as user_id,'2021-08-03' as sigin_date union all select 'uid_1' as user_id,'2021-08-04' as sigin_date union all select 'uid_1' as user_id,'2021-08-01' as sigin_date union all select 'uid_1' as user_id,'2021-08-02' as sigin_date union all select 'uid_1' as user_id,'2021-08-05' as sigin_date union all select 'uid_1' as user_id,'2021-08-06' as sigin_date union all select 'uid_2' as user_id,'2021-08-01' as sigin_date union all select 'uid_2' as user_id,'2021-08-05' as sigin_date union all select 'uid_2' as user_id,'2021-08-02' as sigin_date union all select 'uid_2' as user_id,'2021-08-06' as sigin_date union all select 'uid_3' as user_id,'2021-08-04' as sigin_date union all select 'uid_3' as user_id,'2021-08-06' as sigin_date union all select 'uid_4' as user_id,'2021-08-03' as sigin_date union all select 'uid_4' as user_id,'2021-08-02' as sigin_date ;
2.計算過程
select user_id ,count(1) as sigin_cnt from ( select user_id ,datediff('2021-08-06',sigin_date) as data_diff ,row_number() over (partition by user_id order by sigin_date desc) as row_num from test_sigindate_cnt ) t where data_diff - row_num = -1 group by user_id ;
3.計算結(jié)果及預(yù)期結(jié)果對比
3.1 預(yù)期結(jié)果
匯總?cè)掌?/td> | 用戶id | 登陸天數(shù) |
2021-08-06 | uid_1 | 6 |
2021-08-06 | uid_2 | 2 |
2021-08-06 | uid_3 | 1 |
3.2 計算結(jié)果
以上就是SQL查詢語句求出用戶的連續(xù)登陸天數(shù)的詳細內(nèi)容,更多關(guān)于SQL語句求用戶的連續(xù)登陸天數(shù)的資料請關(guān)注腳本之家其它相關(guān)文章!
相關(guān)文章
sql server編寫archive通用模板腳本實現(xiàn)自動分批刪除數(shù)據(jù)
這篇文章主要介紹了sql server編寫archive通用模板腳本實現(xiàn)自動分批刪除數(shù)據(jù),需要的朋友可以參考下2019-10-10sqlserver數(shù)據(jù)庫中的表、字段sql語句
在數(shù)據(jù)庫中創(chuàng)建的每個對象(例如約束、默認(rèn)值、日志、規(guī)則以及存儲過程)都對應(yīng)一行。2010-06-06數(shù)據(jù)庫日常練習(xí)題,每天進步一點點(1)
下面小編就為大家?guī)硪黄獢?shù)據(jù)庫基礎(chǔ)的幾道練習(xí)題(分享)。小編覺得挺不錯的,現(xiàn)在就分享給大家,也給大家做個參考。一起跟隨小編過來看看吧,希望可以幫到你2021-07-07SQLServer2019 數(shù)據(jù)庫環(huán)境搭建與使用的實現(xiàn)
這篇文章主要介紹了SQLServer2019 數(shù)據(jù)庫環(huán)境搭建與使用的實現(xiàn),文中通過示例代碼介紹的非常詳細,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2021-04-04詳解SQL Server數(shù)據(jù)庫鏈接查詢的方式
本文我們主要介紹了SQL Server數(shù)據(jù)庫鏈接查詢的方式,包括內(nèi)連接、外連接和交叉連接等的內(nèi)容,需要的朋友可以參考下2015-08-08sqlserver四舍五入使用round函數(shù)及cast和convert函數(shù)
大家在遇到sqlserver四舍五入除了用round函數(shù)還有沒有其他方法呢?下面小編給大家介紹使用cast和convert函數(shù),感興趣的朋友一起學(xué)習(xí)吧2015-11-11