WITH today AS( SELECT MAX(DATE(in_time)) FROM tb_user_log ) SELECT user_grade, ROUND(COUNT(uid) / (SELECT COUNT(DISTINCT uid) FROM tb_user_log), 2) AS ratio FROM ( SELECT DISTINCT t1.uid, CASE WHEN DATEDIFF((SELECT * FROM today), min_time) <= 6 THEN '新晋用户' WHEN DATEDIFF((SELECT * FROM today), min_time) > 6 AND DATEDIFF((SELECT * FROM today), max_time) <= 6 THEN '忠实用户' WHEN DATEDIFF((SELECT * FROM today), max_time) > 6 AND DATEDIFF((SELECT * FROM today), max_time) <= 29 THEN '沉睡用户' WHEN DATEDIFF((SELECT * FROM today), max_time) > 29 THEN '流失用户' END AS user_grade FROM ( SELECT uid, DATE(MIN(in_time)) AS min_time, DATE(MAX(in_time)) AS max_time FROM tb_user_log GROUP BY uid ) t1 JOIN tb_user_log t2 ON t1.uid = t2.uid )t2 GROUP BY user_grade ORDER BY ratio DESC
一定要利用好子查询“准备好”要使用的字段,除此之外DISTINCT不能忘了。