题解 | #每个创作者每月的涨粉率及截止当前的总粉丝量#

每个创作者每月的涨粉率及截止当前的总粉丝量

https://www.nowcoder.com/practice/d337c95650f640cca29c85201aecff84

SELECT
    author,
    month,
    ROUND(fans_growth_rate, 3) AS fans_growth_rate,
    SUM(sum_fans) OVER(PARTITION BY author ORDER BY month) AS total_fans
FROM(
    SELECT
        author,
        DATE_FORMAT(end_time, '%Y-%m') AS month,
        AVG(
            CASE
            WHEN if_follow = 1 THEN 1
            WHEN if_follow = 0 THEN 0
            ELSE -1
        END) AS fans_growth_rate,
        SUM(
            CASE
            WHEN if_follow = 1 THEN 1
            WHEN if_follow = 0 THEN 0
            ELSE -1
        END) AS sum_fans
    FROM tb_user_video_log t1
    JOIN tb_video_info t2 ON t1.video_id = t2.video_id
    WHERE YEAR(end_time) = '2021'
    GROUP BY author, month
) t
ORDER BY author, total_fans

关键在于如何累加每个月的粉丝量,这需要使用到SUM+窗口函数。但是SUM内的又应该是已经按照author和month分组汇总好的每个月的粉丝增量,这会非常绕,所以最好将这一部分分组汇总的操作放在子查询中完成,思路会清晰一些。

全部评论

相关推荐

10-09 22:05
666 C++
找到工作就狠狠玩CSGO:报联合国演讲,报电子烟设计与制造
点赞 评论 收藏
分享
扭转乾坤_:现在企业都是学华为,一直通过丢池子里,最后捞
点赞 评论 收藏
分享
1 收藏 评论
分享
牛客网
牛客企业服务