题解 | #每篇文章同一时刻最大在看人数#
每篇文章同一时刻最大在看人数
https://www.nowcoder.com/practice/fe24c93008b84e9592b35faa15755e48
这一题是经典的时间戳内最大的在线人数类问题,但注意最大的坑点在于“同一个时间点先统计进再统计出”这个逻辑,比如在t时刻有3条行为,进、进、出;如果按照先进后出,1、1、-1 对应的sum() over()的当前累积和结果是1,2,1;如果是-1、1、1,则是
-1、0、1;显然当前累积和会受到用户进出行为状态以及排序的影响
select artical_id, max(cnt) max_uv from (select artical_id, time, sum(log) over(partition by artical_id order by time asc,log desc) cnt from (select artical_id, uid, in_time time, 1 log from tb_user_log where artical_id !=0 group by artical_id, uid, in_time union all select artical_id, uid, out_time time, -1 log from tb_user_log where artical_id !=0 group by artical_id, uid, out_time) a ) t1 group by artical_id order by max(cnt) desc