41、现有各直播间的用户访问记录表(live_events)如下,表中每行数据表达的信息为,一个用户何时进入了一个直播间,又在何时离开了该直播间
户访问记录表(live_events)如下
user_id | live_id | in_datetime | out_datetime |
100 | 1 | 2021-12-1 19:30:00 | 2021-12-1 19:53:00 |
100 | 2 | 2021-12-1 21:01:00 | 2021-12-1 22:00:00 |
101 | 1 | 2021-12-1 19:05:00 | 2021-12-1 20:55:00 |
现要求统计各直播间最大同时在线人数,期望结果如下:
live_id | max_user_count |
1 | 4 |
2 | 3 |
3 | 2 |
代码
with t1 as ( -- 时间 动作(登录+1,登出-1) select live_id ,in_datetime as check_time ,1 as action from live_events union all select live_id ,out_datetime as check_time ,-1 as action from live_events )select -- 秒级求最大共同人数 live_id ,max(cn) as max_user_count from ( select -- 时间 累加人数 (开窗sum()只要over()中没有partition by 就能实现累加) live_id ,check_time ,action ,sum(action) over(partition by live_id order by check_time rows between unbounded preceding and current row) as cn from t1 )a group by live_id