计算2021年里每个创作者每月的涨粉率及截止当月的总粉丝量

  1. 截止当月的总粉丝量, 虽然在在where 条件中过滤2021年的数据, 但是在2021年之前如果有粉丝的话, 那么该计算方式就是只能计算2021年截止当月的累计粉丝量
  2. 窗口函数sum() over()的使用, partition by 表示对哪个分组, order by中表示对该列累加
  3. 该题考查对执行顺序的理解, 是先执行group by 再执行窗口函数的, 这点要注意
    select vi.author,
        date_format(ul.start_time, '%Y-%m') as month,
        round(sum(
            case when ul.if_follow=1 then 1
            when ul.if_follow=2 then -1
            else 0 end
        ) / count(1), 3) as fans_growth_rate,
        sum(sum(case when ul.if_follow=1 then 1
            when ul.if_follow=2 then -1
            else 0 end)) over(partition by vi.author order by date_format(ul.start_time, '%Y-%m')) total_fans
    from tb_video_info vi
    join tb_user_video_log ul on vi.video_id=ul.video_id
    where year(ul.start_time) = 2021
    group by vi.author, date_format(ul.start_time, '%Y-%m')
    order by vi.author, total_fans