题解 | #每篇文章同一时刻最大在看人数#

每篇文章同一时刻最大在看人数

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

# 每篇文章同一时刻最大在看人数,想象固定一个门,观察发生浏览人数变化的时刻点统计其进入和离开的人数
# (1)将各记录分成两个,一个记录进入时间,一个记录离开时间,然后联合两表
with t1 as
(select artical_id, in_time tag_time, 1 tag
from tb_user_log
where artical_id <> 0
union all
select artical_id, out_time tag_time, -1 tag
from tb_user_log
where artical_id <> 0)

# (2)使用窗口函数计算对每篇文章而言各个浏览人数发生变化的时刻点的在看人数,然后计算每篇文章同一时刻最大在看人数
select artical_id, max(current_num) max_uv
from (
    select artical_id, sum(tag)over(partition by artical_id order by tag_time, tag desc) current_num
    from t1
) t2
group by artical_id
order by max_uv desc;

全部评论

相关推荐

头像
10-27 15:50
门头沟学院 Java
想进开水团喝开水:有一种店 只能外卖 不能堂食 你猜为什么
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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