题解 | #计算用户的平均次日留存率#
计算用户的平均次日留存率
https://www.nowcoder.com/practice/126083961ae0415fbde061d7ebbde453
两种解法
解法一:
# 方法一:用左连接 SELECT COUNT(date2)/ COUNT(date1) AS avg_ret FROM ( SELECT DISTINCT qpd.device_id, qpd.date AS date1, uniq_id_date.date AS date2 FROM question_practice_detail AS qpd LEFT JOIN ( SELECT DISTINCT device_id, date FROM question_practice_detail ) AS uniq_id_date ON qpd.device_id = uniq_id_date.device_id AND DATE_ADD(qpd.date, INTERVAL 1 DAY) = uniq_id_date.date ) AS id_last_next_date
解法二:
# 方法二:由内而外展开,理解这个问题,为什么要加distinct SELECT AVG(IF(DATEDIFF(date2, date1) = 1, 1, 0)) AS avg_ret FROM ( SELECT device_id, date AS date1, LEAD(date) OVER (PARTITION BY device_id ORDER BY date) AS date2 FROM ( SELECT DISTINCT device_id, date FROM question_practice_detail ) AS uniq_id_date ) AS id_last_next_date
几个注意点
- 客户次日留存率是什么
- 所有子查询必须取别名
- date_add(your_date, INTERVAL expr TYPE)
expr可以是数字,也可以是表达式,TYPE可以是年、天、月、时、分、秒
4. DISTINCT作用于多个属性,直接在DISTINCT后面加上属性的名称
SELECT DISTINCT device_id, date FROM question_practice_detail