如下需求:
一张表有如下字段:
1)直播间: live_id
2)用户:userid
3)时间戳:date_stamp
4)登陆类型:entry_type (登入和登出)
求直播间在某一天同一时间点的最大在线用户数?
逻辑说明:
将直播间每登陆一个记为1,每登出一个记为-1,如此将会登陆和登出出现抵消,然后再根据时间进行排序求和。
WITH live_tab as (
select 1 live_id,'A' userid,to_date('20200801 10:00:00','yyyymmdd hh24:mi:ss') date_stamp ,'enter' entry_type from dual
union all
select 1 live_id,'B' userid,to_date('20200801 10:01:00','yyyymmdd hh24:mi:ss') date_stamp ,'enter' entry_type from dual
union all
select 1 live_id,'C' userid,to_date('20200801 10:02:03','yyyymmdd hh24:mi:ss') date_stamp ,'enter' entry_type from dual
union all
select 1 live_id,'D' userid,to_date('20200801 10:04:03','yyyymmdd hh24:mi:ss') date_stamp ,'enter' entry_type from dual
union all
select 1 live_id,'A' userid,to_date('20200801 10:03:10','yyyymmdd hh24:mi:ss') date_stamp ,'out' entry_type from dual
union all
select 1 live_id,'C' userid,to_date('20200801 10:03:11','yyyymmdd hh24:mi:ss') date_stamp ,'out' entry_type from dual
union all
select 1 live_id,'A' userid,to_date('20200801 10:04:00','yyyymmdd hh24:mi:ss') date_stamp ,'enter' entry_type from dual
union all
select 1 live_id,'F' userid,to_date('20200801 10:04:06','yyyymmdd hh24:mi:ss') date_stamp ,'enter' entry_type from dual
union all
select 1 live_id,'G' userid,to_date('20200801 10:04:10','yyyymmdd hh24:mi:ss') date_stamp ,'enter' entry_type from dual
union all
select 1 live_id,'H' userid,to_date('20200801 10:04:12','yyyymmdd hh24:mi:ss') date_stamp ,'enter' entry_type from dual
union all
select 1 live_id,'I' userid,to_date('20200801 10:05:10','yyyymmdd hh24:mi:ss') date_stamp ,'out' entry_type from dual
)
select live_id,userid, date_stamp,sum(flag) over (order by date_stamp)
from
(select live_id, userid, date_stamp as date_stamp, case when entry_type = 'enter' then 1
when entry_type = 'out' then -1 else 0 end flag
from live_tab lt1
);