题解 | #每篇文章同一时刻最大在看人数#
每篇文章同一时刻最大在看人数
http://www.nowcoder.com/practice/fe24c93008b84e9592b35faa15755e48
难点在于计算某时刻在看人数!!!解题关键应用窗口函数计算,大概思路就是 sum(uv) over (partition by artical_id order by time)
首先,计算每一时刻的人数变动
- 每条记录的进入时间表示进入人数多了1:SELECT artical_id, in_time as dt,1 as uv FROM tb_user_log
- 每条记录的离开时间表示离开人数多了1:SELECT artical_id, out_time as dt, -1 as uv FROM tb_user_log
- 合并上面两个结果:UNION ALL(备注:运算对象的记录的列数必须相同(每部分列名及列的类型可以不同))
然后,计算当前时间再看人数总和,使用窗口函数sum(),在此需要注意按照【先进后出】原则(如果同一时刻有进入也有离开时,先记录用户数增加,再记录减少),所以排序需要注意(order by uv desc)。
- sum(uv) over (partition by artical_id order by dt,uv desc)
综上,代码如下
select t1.artical_id,max(t1.insant_uv) max_uv FROM (select t.artical_id, t.dt, sum(t.uv) over (partition by t.artical_id order by t.dt,t.uv desc) insant_uv from (SELECT artical_id,in_time dt,1 as uv from tb_user_log where artical_id != 0 union all SELECT artical_id,out_time dt,-1 as uv from tb_user_log where artical_id != 0 order by artical_id,dt)t)t1 GROUP BY t1.artical_id order by max_uv desc;