Mysql计算n日留存率的实现
时间:2023-02-01阅读:6来源:柠檬博客作者:柠檬博客
目录
一、创建一张包含每个用户最早登入日期的表
select user_id,min(date) as first_day from a2_userbehavior_csv group by user_id二、创建一张包含每个用户所有登入日期的表
实际上就是对用户和日期去重
select user_id,date from a2_userbehavior_csv group by user_id,date三、将两个表按照user_id拼接,并且计算日期时间差
select t1.*,t2.date,datediff(t2.date,t1.first_day) as day_diff from (select user_id,min(date) as first_day from a2_userbehavior_csv group by user_id) as t1 left join (select user_id,date from a2_userbehavior_csv group by user_id,date) as t2 on t1.user_id=t2.user_id
得到结果如下:
得到了每个用户每个登入日期距离其最早登入日期的天数。
四、计算各种留存率现在思路就明朗了。
次日留存率=(day_diff=1的数量)/(day_diff=0的数量)
三日留存率=(day_diff=3的数量)/(day_diff=0的数量)
select first_day as dt, concat(round(100*count(case when day_diff=1 then user_id end)/count(case when day_diff=0 then user_id end),2),"%") as '次日留存率', concat(round(100*count(case when day_diff=3 then user_id end)/count(case when day_diff=0 then user_id end),2),"%") as '三日留存率', concat(round(100*count(case when day_diff=7 then user_id end)/count(case when day_diff=0 then user_id end),2),"%") as '七日留存率' from (select t1.*,t2.date,datediff(t2.date,t1.first_day) as day_diff from (select user_id,min(date) as first_day from a2_userbehavior_csv group by user_id) as t1 left join (select user_id,date from a2_userbehavior_csv group by user_id,date) as t2 on t1.user_id=t2.user_id) as t3 group by first_day order by first_day原文地址:https://blog.csdn.net/weixin_44020827/article/details/122906062
6人参与,
0条评论
登录后显示评论回复