用户留存率SQL题
Posted wzy0623
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了用户留存率SQL题相关的知识,希望对你有一定的参考价值。
-- 方法一
SELECT t0.date, IFNULL(ROUND(COUNT(DISTINCT t2.user_id) / (COUNT(t1.user_id)),3),0)
FROM (SELECT date FROM login GROUP BY date) t0
LEFT JOIN (SELECT user_id, MIN(date) AS date FROM login GROUP BY user_id) t1 ON t0.date = t1.date
LEFT JOIN login AS t2 ON t1.user_id = t2.user_id AND DATEDIFF(t2.date, t1.date) = 1
GROUP BY t0.date;
-- 方法二
SELECT date, IFNULL(ROUND((SUM(CASE WHEN (user_id , date) IN (SELECT user_id, DATE_ADD(date, INTERVAL - 1 DAY) FROM login) AND
(user_id , date) IN (SELECT user_id, MIN(date) FROM login GROUP BY user_id)
THEN 1
ELSE 0
END)) /
(SUM(CASE WHEN (user_id , date) IN (SELECT user_id, MIN(date) FROM login GROUP BY user_id)
THEN 1
ELSE 0
END)),
3),0) AS p
FROM login
GROUP BY date
ORDER BY date;
(注:方法一的3表关联对大表来说必须加索引,方法二的子查询方式不推荐
create index idx_date on login(date);
create index idx_user_id_date on login(user_id,date);
)
以上是关于用户留存率SQL题的主要内容,如果未能解决你的问题,请参考以下文章