step1:拆解题目
1、若想统计“同一时刻”的“最大”观看人数,那就先要统计《每个》“同一时刻”的“观看人数”;
2、若想统计《每个》“同一时刻”的“观看人数”,那就先要理解“同一时刻”的内涵(观众“观看”or“停止”时间点👉人员变动时刻👉观看人数变动时刻👉“同一时刻”)【错误理解:将“同一时刻”理解成每秒,然后统计每秒的观看人数。错误原因:我们的目标是统计“最大”观看人数,那必然是在“观看人数变动时刻”才会存在“最值”,而只有在观众“观看”or“停止”时间点,观看人数才会发生变动,那么就只需要统计观众在“观看”or“停止”的时间点上的人数即可】

step2:实操
3、若想统计每个《观众在“观看”or“停止”的时间点》上的人数,那就可以先将《观众开始观看时间——in_time》设为1(即为人数+1),《观众停止观看时间——out_time》设为-1(即人数-1)【定义数字字段是为了方便统计人数的变动】,然后用union all函数将进行求并集,得到每个“特殊时刻”的“时点人数增减情况”代码如下:
(select artical_id,in_time as time,1 as number
from tb_user_log
where artical_id != 0

union all

select artical_id,out_time as time,-1 as number
from tb_user_log
where artical_id != 0
order by 1,2)
运行结果:
1	9001|2021-11-01 10:00:00|1	1	
2	9001|2021-11-01 10:00:01|1	2	
3	9001|2021-11-01 10:00:09|1		
4	9001|2021-11-01 10:00:11|-1		
5	9001|2021-11-01 10:00:28|1		
6	9001|2021-11-01 10:00:38|-1		
7	9001|2021-11-01 10:00:51|1		
8	9001|2021-11-01 10:00:58|-1		
9	9001|2021-11-01 10:00:59|-1		
10	9001|2021-11-01 10:01:50|-1		
11	9002|2021-11-01 11:00:45|1		
12	9002|2021-11-01 11:00:55|1		
13	9002|2021-11-01 11:01:11|-1		
14	9002|2021-11-01 11:01:24|-1

4、之后用窗口函数计算“特殊时刻”的人数变动情况【按照artical_id进行分组,组内按照《观看时间》进行正序排序(注意:要将in_time和out_time放置于1个字段内)】《注意要求:如果同一时刻有进入也有离开时,先记录用户数增加再记录减少👉在对时间进行正向排序之后,若存在同一时刻,则要先计算+1,再计算-1,因此要进行number字段的倒序排序》,代码如下:
(select t1.artical_id,t1.time,
sum(t1.number) over(partition by t1.artical_id order by t1.time,t1.number desc) as uv
from
(select artical_id,in_time as time,1 as number
from tb_user_log
where artical_id != 0

union all

select artical_id,out_time as time,-1 as number
from tb_user_log
where artical_id != 0
order by 1,2) as t1)
运行结果:
1	9001|2021-11-01 10:00:00|1	
2	9001|2021-11-01 10:00:01|2	
3	9001|2021-11-01 10:00:09|3		
4	9001|2021-11-01 10:00:11|2		
5	9001|2021-11-01 10:00:28|3		
6	9001|2021-11-01 10:00:38|2		
7	9001|2021-11-01 10:00:51|3		
8	9001|2021-11-01 10:00:58|2		
9	9001|2021-11-01 10:00:59|1		
10	9001|2021-11-01 10:01:50|0		
11	9002|2021-11-01 11:00:45|1		
12	9002|2021-11-01 11:00:55|2		
13	9002|2021-11-01 11:01:11|1		
14	9002|2021-11-01 11:01:24|0

5、再利用max函数配合group by分组统计,求出每个“特殊时刻”中、存在最多人数的“特殊时刻”,对结果及逆行排序


整体代码如下:
select t2.artical_id,max(t2.uv) as max_uv
from
(select t1.artical_id,t1.time,
sum(t1.number) over(partition by t1.artical_id order by t1.time,t1.number desc) as uv
from
(select artical_id,in_time as time,1 as number
from tb_user_log
where artical_id != 0

union all

select artical_id,out_time as time,-1 as number
from tb_user_log
where artical_id != 0
order by 1,2) as t1) as t2
group by 1
order by 2 desc