在会话日志表中查找最大并发用户

时间:2019-01-07 19:15:56

标签: sql oracle

我需要找到最大并发用户数(如果有,请加上日期时间)

我的表t_sessions包含10,800,000行,如下所示:

sesion_start      duration_in_sec  user_name
01/01/2019 01:00  280              a
01/01/2019 01:02  380              b
01/01/2019 01:01  1250             c

我需要找到最大并发用户(如果适用,请显示其日期时间) 我创建了一个临时表t_times包含以秒为单位的所有时间:

f_time
01/01/2019 00:00:01
01/01/2019 00:00:02
01/01/2019 00:00:03

select max(c) from
(select f_time, count(*) c
 from t_times a
 join t_sessions b 
     on a.f_time between sesion_start and
                         (sesion_start  + (duration_in_sec /86400))
 group by f_time)

运行这种查询是否有更低的成本和更好的方法?

1 个答案:

答案 0 :(得分:1)

是的,您可以使用“输入/输出”逻辑:

with t as (
      select session_start as td, 1 as inc
      from t_sessions t
      union all
      select session_start + (duration_in_sec / (24*60*60)), inc  -- old-fashioned method.  I'm being lazy
              -1 as inc
      from t_sessions t
     )
select t.*
from (select t.*,
             row_number() over (order by num_concurrent desc) as seqnum
      from (select t.td, sum(inc) over (order by t.td) as num_concurrent
            from t
            order by num_concurrent desc
           ) t
      ) t
where seqnum = 1;

这可能会有轻微的偏离1的差异,具体取决于查找秒是否作为并发用户包括在内。

这还假设您的查询隐含了单个用户的会话不重叠。