题解 | 每篇文章同一时刻最大在看人数
每篇文章同一时刻最大在看人数
https://www.nowcoder.com/practice/fe24c93008b84e9592b35faa15755e48
思路:首先筛掉不符合的artical_id = 0 的情况,接着通过打标签的方式,将in_time和out_time转为一列,使用1和-1进行区分,使用sum开窗函数累加得到每次人数发生变化时的在线人数,求max,作order处理。
-- 筛 artical_id = 0
-- 打标签in 1 out -1
-- sum() over 按文章
-- desc
with t1 as (
select
artical_id,
in_time,
out_time
from tb_user_log
where artical_id != 0
)
select
artical_id,
max(uv) as max_uv
from(
select
artical_id,
sum(flag) over(partition by artical_id order by view_time asc, flag desc) uv
from(select
artical_id,
in_time as view_time,
1 as flag
from t1
union all
select
artical_id,
out_time as view_time,
-1 as flag
from t1)t2
)t3
group by artical_id
order by max_uv desc
