题解 | #统计活跃间隔对用户分级结果#

统计活跃间隔对用户分级结果

https://www.nowcoder.com/practice/6765b4a4f260455bae513a60b6eed0af

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不能忘了。

全部评论

相关推荐

尊尼获获:闺蜜在哪?
点赞 评论 收藏
分享
offer多多的六边形战士很无语:看了你的博客,感觉挺不错的,可以把你的访问量和粉丝数在简历里提一下,闪光点(仅个人意见)
点赞 评论 收藏
分享
1 收藏 评论
分享
牛客网
牛客企业服务