select author, date_format(start_time, '%Y-%m') as month, 
round(SUM(case when if_follow=1 then 1
    when if_follow=2 then -1
   else 0
   end)/ COUNT(start_time), 3) fans_growth_rate,
sum(sum(if(if_follow = 2, -1, if_follow))) over(partition by author order by date_format(start_time, '%Y-%m')) total_fans
from tb_user_video_log join tb_video_info using(video_id)
where year(start_time) = 2021
group by author, month
order by author desc, total_fans asc               

这道题需要注意的地方是求截止当月的总粉丝量,而不是求每个月单独的总粉丝数,比如一月份我的新增粉丝10,掉了2个,我一个月份总粉丝为8个;二月份我的新增粉丝为6个,掉了3个,那么【截止到二月】我的总粉丝为(10-2)+ (6-3)=11个。
所以同上,这道题在求截止当月的总粉丝量就是累加前几个月(新增粉丝-取消关注)的数量。
这里不能用只用一个sum(if()),需要结合窗口函数,在外再加一个sum,所以第一个sum是针对每一个月内单独计算,第二个sum是为了粉丝量在不同月份的累加。