题解 | #每个创作者每月的涨粉率及截止当前的总粉丝量#
每个创作者每月的涨粉率及截止当前的总粉丝量
https://www.nowcoder.com/practice/d337c95650f640cca29c85201aecff84
## 选取答案要的字段--该表的粒度是2021年某月作者的涨粉率和总粉丝量
select
## 作者
author,
## 年月
month,
## 涨粉率
cast(this_month_add/play_video_num as decimal(16,3)) `fans_growth_rate`,
## 在本年中,累加截止本行的年月的涨粉数就是总粉丝数
sum(this_month_add) over(partition by author order by month rows between unbounded preceding and current row) total_fans
from
(
## 该表粒度是作者本年月的涨粉数,掉粉数,累加涨粉数
select
## 视频作者
author,
## 年月
month,
## 播放数
count(*) `play_video_num`,
## 涨粉数
sum(if (if_follow = 1, 1, 0)) `add`,
## 掉粉数
sum(if (if_follow = 2, -1, 0)) `sub`,
## 本月涨粉数
sum(if (if_follow = 1, 1, 0))+sum(if (if_follow = 2, -1, 0)) `this_month_add`
from
(
##在2021年中,每个用户播放一次视频的记录
select
## 视频的作者
author,
## 该记录的年月
date_format (end_time, "%Y-%m") `month`,
## 涨粉或掉分记录
if_follow
from
tb_user_video_log tuvl
## 内连接
inner join tb_video_info tvi on tuvl.video_id = tvi.video_id
## 过滤出2021年数据
where
year (end_time) = '2021'
) t1
根据作者和年月分组
group by
author,
month
) t2
## 按照作者和总粉丝数升序排序
order by author,total_fans

查看1道真题和解析