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

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

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

【问题分析】

对于不同的时间截点,有人登入有人登出,这个时候就存在一个同时在线人数高峰,我们要做的就是分作品找到这个时间高峰。

人数高峰时间不确定,其随着人的登入与登出在变动,登入人数增加,登出人数减少,一个自然的想法是对所有登入与登出时间编码,然后对时间截点分作品累加,然后再统计最大值出现的点即可。

【问题求解】

第一步:对登入与登出时间进行编码。

select 
	artical_id
	,in_time as time
	,1 as person_diff
from tb_user_log
where artical_id <> 0
union
select
	artical_id
	,out_time as time
	,-1 person_diff
from tb_user_log
where artical_id <> 0
	

第二步:对不同时间截点按照artical_id分组求和。

select
	artical_id
	,sum(person_diff) over(partition by artical_id order by time,person_diff desc) as max_uv
from (
select 
	artical_id
	,in_time as time
	,1 as person_diff
from tb_user_log
where artical_id <> 0
union
select
	artical_id
	,out_time as time
	,-1 person_diff
from tb_user_log
where artical_id <> 0
) t1

	

第三步:返回结果

select
	artical_id
	,max(max_uv) as max_uv
from (
select
	artical_id
	,sum(person_diff) over(partition by artical_id order by time,person_diff desc) as max_uv
from (
select 
	artical_id
	,in_time as time
	,1 as person_diff
from tb_user_log
where artical_id != 0
union all
select
	artical_id
	,out_time as time
	,-1 person_diff
from tb_user_log
where artical_id != 0
) t1
) t2
group by artical_id
order by max_uv desc
;
#SQL练习记录#
全部评论

相关推荐

不愿透露姓名的神秘牛友
12-18 11:21
优秀的大熊猫在okr...:叫你朋友入职保安,你再去送外卖,一个从商,一个从政,你们两联手无敌了,睁开你的眼睛看看,现在是谁说了算(校长在背后瑟瑟发抖)
选实习,你更看重哪方面?
点赞 评论 收藏
分享
11-23 15:33
已编辑
门头沟学院 Java
CUTMR:换账号试试重启推荐算法,我换账号之后回复率还不错,约莫有个20%左右的消息回复率,前几页、主动招呼的HR也开始符合我期望薪资,此前的大号从招呼、回复、前几页的岗位薪资在涨幅30%+以上 用着用着聊着聊着就变成-20%,而且我开通会员之后直接0面试
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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