题解 | #统计活跃间隔对用户分级结果#
统计活跃间隔对用户分级结果
http://www.nowcoder.com/practice/6765b4a4f260455bae513a60b6eed0af
- 查找每个用户最早登录时间first_time以及最晚登录时间recent_time,利用窗口函数找出所有用户中最晚的登陆时间today,形成表t1
- 对t1表中用户进行分级,为减少判断次数,可以先判断新晋用户再判断忠实用户,形成表t2
- 对t2表中的各等级用户,利用聚合函数和窗口函数统计得到ratio
select
user_grade,
round(count(*) / sum(count(*)) over(), 2) ratio
from
(select
case
when datediff(today, first_time) between 0 and 6 then '新晋用户'
when datediff(today, recent_time) between 0 and 6 then '忠实用户'
when datediff(today, recent_time) >= 29 then '流失用户'
else '沉睡用户'
end user_grade
from
(select
max(date(in_time)) recent_time,
min(date(in_time)) first_time,
max(max(date(in_time))) over() today
from
tb_user_log
group by
uid) t1) t2
group by
user_grade
order by
ratio desc;