景:產品作了一個週期7天活動,用戶能夠每一天解鎖一個任務,完成後發放獎勵;微信
需求:按日統計連續完成N天用戶數
app
目的:用戶參與活動的興趣度;函數
活動海報圖:
ui
分析思路:spa
這就是連續登錄問題,用至關時間差斷定;.net
用戶明細以下:3d
借用lag函數斷定上一次登錄日期;orm
連續登錄幾天,其datediff日期差等於連續登錄天數blog
附上代碼:ci
,with tmp_da_user as (
select
to_date(ds,'yyyymmdd') as ds
,uid
,count(distinct ds) as 完整天數
from tmp_t_user_takse_detail
where status_name = '完成'
and uid in ('203111313364823804','1833903495100023')
group by
ds
,uid
)
,tmp_da_user_tack as (
select *
,lag(ds,1)over(partition by uid order by ds asc) as lag_1
,lag(ds,2)over(partition by uid order by ds asc) as lag_2
,lag(ds,3)over(partition by uid order by ds asc) as lag_3
,lag(ds,4)over(partition by uid order by ds asc) as lag_4
,lag(ds,5)over(partition by uid order by ds asc) as lag_5
,lag(ds,6)over(partition by uid order by ds asc) as lag_6
,lag(ds,7)over(partition by uid order by ds asc) as lag_7
from tmp_da_user
)
select
ds
,count(distinct uid) as 當天完成任務數
,count(case when DATEDIFF(ds,lag_1,'dd') = 1 then uid end ) as 連續2天完成
,count(case when DATEDIFF(ds,lag_2,'dd') = 2 then uid end ) as 連續3天完成
,count(case when DATEDIFF(ds,lag_3,'dd') = 3 then uid end ) as 連續4天完成
,count(case when DATEDIFF(ds,lag_4,'dd') = 4 then uid end ) as 連續5天完成
,count(case when DATEDIFF(ds,lag_5,'dd') = 5 then uid end ) as 連續6天完成
,count(case when DATEDIFF(ds,lag_6,'dd') = 6 then uid end ) as 連續7天完成
,count(case when DATEDIFF(ds,lag_7,'dd') = 7 then uid end ) as 連續8天完成
from tmp_da_user_tack
group by ds
本文分享自微信公衆號 - SQL數據分析(dianwu_dw)。
若有侵權,請聯繫 support@oschina.cn 刪除。
本文參與「OSC源創計劃」,歡迎正在閱讀的你也加入,一塊兒分享。