select author, `month`, round(fans_add_cnt / play_cnt, 3) as fans_growth_rate,
sum(fans_add_cnt) over(partition by author order by `month`) as total_fans
from (
select author,
date_format(start_time, "%Y-%m") as `month`,
sum(if(if_follow = 2, -1, if_follow)) as fans_add_cnt,
count(1) as play_cnt
from tb_user_video_log
join tb_video_info using (video_id)
where year(start_time) = 2021
group by author, `month`
) as t_author_monthly_fans_play_cnt
order by author, total_fans;
内层子查询 (
t_author_monthly_fans_play_cnt
):这个子查询首先从tb_user_video_log
表和tb_video_info
表中选择数据,通过video_id
列进行连接。然后,它使用DATE_FORMAT
函数来格式化start_time
列为"YYYY-MM"
格式的月份。接着,它计算每个作者每个月的粉丝增加数量(fans_add_cnt
)和播放次数(play_cnt
)。粉丝增加数量是通过if_follow
列来判断的,如果if_follow
等于2,则表示减少一个粉丝,否则表示增加一个粉丝。播放次数是通过计算每个月的记录数来得到的。最后,它按作者和月份进行分组。外层查询:外层查询使用内层子查询的结果,并使用
ROUND
函数来计算粉丝增长率(fans_growth_rate
),这是通过将fans_add_cnt
除以play_cnt
并四舍五入到小数点后三位来计算的。然后,它使用SUM
窗口函数和OVER
子句来计算每个作者每月的累计粉丝数(total_fans
),这是通过PARTITION BY author
按作者分区并在ORDER BY
month``的月份顺序上计算的累积和。排序:最后,查询使用
ORDER BY author, total_fans
来按作者和累计粉丝数进行排序。整个查询的逻辑是先计算出每个作者在2021年每个月的粉丝增加数量和播放次数,然后计算出每个作者的粉丝增长率和累计粉丝数,并按照作者和累计粉丝数进行排序。