题解 | #每个创作者每月的涨粉率及截止当前的总粉丝量#

每个创作者每月的涨粉率及截止当前的总粉丝量

https://www.nowcoder.com/practice/d337c95650f640cca29c85201aecff84

# 字段:author、month、每月涨粉率fans_growth_rate、total_fans
# # tb1:连接
with tb1 as(
    select uid,author,date_format(start_time,'%Y-%m') as start_date,if_follow,
    # 增加关注字段
    if(if_follow = 2,-1,if_follow) as follow
    # 播放量
    from tb_user_video_log left join tb_video_info using(video_id)
    where year(start_time) = 2021
)
# tb2:
# 涨粉率 = (加粉量-掉粉量)/播放量
# tb2 as(
    select author,start_date,
    # count(if(follow=1,follow,null)),count(if(follow=-1,follow,null)),count(follow),
    round((count(if(follow=1,follow,null))-count(if(follow=-1,follow,null)))/count(follow),3) as fans_growth_rate,
    # 总粉丝数
    sum(sum(follow)) over(partition by author order by start_date) as total_fans

    from tb1
    group by author,start_date
    order by author , sum(sum(follow)) over(partition by author order by start_date) 
# )

# tb3:求取累计粉丝数, 需要解决sum()over()和group by的共存问题
# select distinct author,start_date,fans_growth_rate,
# sum(follow)over(partition by author order by start_date) as total_fans
# from tb1 left join tb2 using(author,start_date)






# SELECT author, date_format(start_time,'%Y-%m') month,
# # 涨粉率
# round(sum(case when if_follow=1 then 1
#                when if_follow=2 then -1
#                else 0 end)/count(author),3) fans_growth_rate,

# sum(sum(case when if_follow=1 then 1 when if_follow=2 then -1 else 0 end)) # follow//
# over(partition by author order by date_format(start_time,'%Y-%m')) total_fans
# FROM tb_user_video_log log 
# left join tb_video_info info on log.video_id=info.video_id
# where year(start_time)=2021
# group by author,month
# order by author,total_fans  

# 这个版本可以,是因为sum()over()内部已经聚合了一个sum


































全部评论

相关推荐

07-14 12:22
门头沟学院 Java
点赞 评论 收藏
分享
06-26 22:20
门头沟学院 Java
码农索隆:让你把简历发给她,她说一些套话,然后让你加一个人,说这个人给你改简历,然后开始卖课
我的求职精神状态
点赞 评论 收藏
分享
自学java狠狠赚一...:骗你点star的,港卵公司,记得把star收回去
点赞 评论 收藏
分享
评论
1
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务