select 
author,
date_format(start_time, '%Y-%m') as watched_month,
# sum(if(if_follow=1,1,0)),
# sum(if(if_follow=2,1,0)),
# count(*),
round((sum(if(if_follow=1,1,0)) - sum(if(if_follow=2,1,0))) / count(*),3) as fans_growth_rate,
sum(sum(case when if_follow = 1 then 1
             when if_follow = 2 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 a left join tb_video_info b on a.video_id = b.video_id
where year(start_time) = 2021
group by author,watched_month
order by author,total_fans

这题最关键的点在于需要累积用户每个月的粉丝数,如果只用groupby函数,只能分别获取每个月的涨粉数、掉粉数和总变化数。

而题目要求输出每个月的累计粉丝数,就要用到上个月的粉丝变化数,因此卡住不会写了。

认识了新函数,窗口函数,他也经常和聚合函数一起出来使用,两个sum函数,里面那个旨在聚合函数下计算每个月的粉丝变化数,而外面那个则是结合窗口函数来计算累加。ps:一般窗口函数外面都是要配合个函数进行操作的。