问题描述
你正在搭建一个用户活跃度的画像,其中一个与活跃度相关的特征是“最长连续登录天数”, 请用SQL实现“2023年1月1日-2023年1月31日用户最长的连续登录天数”
数据表结构
- 登陆表 tb_dau:
| fdate | user_id |
|---|---|
| 2023-01-01 | 10000 |
备注: MySQL中日期加减的函数
- 日期增加 DATE_ADD,
- 日期减少 DATE_SUB,
- 日期差 DATEDIFF,例:datediff('2023-02-01', '2023-01-01') 输出31
解题思路
① 排序后并计算start_day
-- 提取2023年1月数据
-- 根据登录时间排序(row_number)
-- 根据排序计算连续登录的第一天start_day,如果连续,start_day会一致
with step1 as
(Select user_id
, row_number() over(partition by user_id order by fdate asc) as ranking -- 可不用添加该列
, date_sub(fdate, interval row_number() over(partition by user_id order by fdate asc) day ) as start_day
From tb_dau
Where left(fdate, 7) = '2023-01'),
② 分组求连续次数
-- 根据start_day求连续登录天数
step2 as(
Select user_id
, start_day
, count(start_day) as consec_days
from step1
group by user_id
, start_day
)
③ 取最长天数
-- 得到最长连续天数
Select user_id
, max(consec_days) as max_consec_days
from step2
group by user_id

京公网安备 11010502036488号