# 每一秒为1个时刻,这张表格记录着,在这1秒的某个文章上,这个行为是登入,还是登出,以及对应的时间 with in_out_count as( select artical_id, in_time as time, 1 as mark from tb_user_log where artical_id != 0 union all ### 需要全都匹配 select artical_id, out_time as time, -1 as mark from tb_user_log where artical_id != 0 ), # 以文章分组,计算每一个文章,在每一个时刻上的人数(登入的人数-登出的人数) #按照 时间,登入还是登出排序,形成如下的时间轴 # 时间轴: 1 2 3 4 # 用户1: ↑ ↓ # 用户2: ↑ ↓ # 用户3: ↑ ↓ # 想象从时间轴1,到2,一直到4扫描,每个时刻上 # OVER(...)窗口函数 , 默认范围是从分区第一行到当前行,相当于一个滑动窗口,逐行计算累计值 record_second as( select artical_id, sum(mark) over (partition by artical_id order by time, mark desc) as cnt from in_out_count ) select artical_id, max(cnt) as max_uv from record_second group by artical_id order by max_uv desc