模拟场景
例如登陆表
解决方案
1、思路:
把登陆时间、和登出时间看成一个动作,登录就+1人,登出就-1人。然后每个时间进行累加所有的人。即可看出每个时间点的在线人数。
2、代码
1、把登录时间、登出时间、动作 汇聚成一张临时表
with t1 as (
-- 时间 动作(登录+1,登出-1)
select
login_ts as check_time
,1 as cnt
from user_login_detail
union all
select
logout_ts as check_time
,-1 as cnt
from user_login_detail
)
2、累加在线人数
select
-- 秒级求最大共同人数
max(cn) as cn
from (
select
-- 时间 累加人数 (开窗sum()只要over()中没有partition by 就能实现累加)
check_time
,sum(cnt) over(order by check_time) as cn
from t1
)a
3、求最大
select
-- 秒级求最大共同人数
max(cn) as cn
from (
select
-- 时间 累加人数 (开窗sum()只要over()中没有partition by 就能实现累加)
check_time
,sum(cnt) over(order by check_time) as cn
from t1
)a