SQL查詢語句求出使用者的連續登陸天數

2022-09-20 10:30:11 字數 2245 閱讀 9698

求解使用者登陸資訊表中,每個使用者連續登陸平台的天數,連續登陸基礎為彙總日期必須登陸,表中每天只有一條使用者登陸資料(計算中不涉及天內去重)。

表描述:user_id:使用者的id;

sigin_date:使用者的登陸日期。

注:求解過程有多種方式,下述求解解法為筆者思路,其他解法可在評論區交流。

思路:該問題的突破的在於登陸時間,計算得到連續登陸標識,以標識分組為過濾條件,得到連續登陸的程式設計客棧天數,最後以user_id分組,以count()函式求和得到每個使用者的連續登陸天數。

連續登陸標識 =(當日登陸日期 - 使用者的登陸日期)- 開窗排序的順序號(倒序)

-- 1.建表語句

drop table if exists test_sigindate_cnt;

create table tjepeelzest_sigindate_cnt(

user_id string

,sigin_date string );

-- 2.測試資料插入語句

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,'20' 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

;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

) twhere data_diff - row_num = -1

group by

user_id

;3.1 預期結果 

彙總日期

使用者id

登陸天數

程式設計客棧 2021-08-06

uid_1

62021-08-06

uid_2

22021-08-06

uid_3

13.2 計算結果

sql倒序查詢語句 常見的SQL查詢語句

檢視會話數 select count from v session 檢視程序數 select count from v process 檢視資料庫的併發連線數 select from v session where status active 檢視當前資料庫建立的會話 select sid,seri...

SQL 的查詢語句,模糊查詢

一般模糊語句如下 select 字段 from 表 where 某欄位 like 條件 其中關於條件,sql提供了四種匹配模式 1,表示任意0個或多個字元。可匹配任意型別和長度的字元,有些情況下若是中文,請使用兩個百分號 表示。比如 select from user where u name lik...

SQL查詢至少連續七天下單的使用者

create table orde id varchar 10 date datetime,orders varchar 10 insert into orde values 1 2019 1 1 10 insert into orde values 1 2019 1 2 109 insert in...