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

select v.author,date_format(u.start_time,'%Y-%m') as month, round(sum(case when u.if_follow=1 then 1 when u.if_follow=0 then 0 when u.if_follow=2 then -1 End)/count(u.start_time),3) fans_growth_rate, sum(sum(case when if_follow = 2 then -1 when if_follow = 1 then 1 else 0 end)) over(partition by author order by date_format(start_time,"%Y-%m"))  as total_fans
from tb_user_video_log u 
right join tb_video_info v on v.video_id=u.video_id
where date_format(u.start_time,'%Y')=2021
and date_format(u.end_time,'%Y')=2021
group by v.author, date_format(u.start_time,'%Y-%m')
order by v.author, total_fans

在计算每月的总粉丝量时,我们需要知道每个月的粉丝净增长量(即新增粉丝数减去取消关注的粉丝数),并且需要将这些净增长量累加起来,以得到每个月的总粉丝量。由于我们需要按月和按作者分别计算,因此不能简单地使用 SUM 函数,因为它会将所有数据汇总在一起,而不是按月和按作者分别累加。

窗口函数(Window Function)在这里非常有用,因为它允许我们在不改变数据分组的情况下进行计算。具体来说,我们可以使用 SUM 窗口函数来计算每个月的总粉丝量,同时按作者进行分区(Partition)。

全部评论

相关推荐

评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务