Sql 如何计算给定会话日志的峰值并发用户数

Sql 如何计算给定会话日志的峰值并发用户数,sql,google-sheets,google-bigquery,Sql,Google Sheets,Google Bigquery,我有会话开始时间、会话结束时间和持续时间(以小时为单位)。我正试图找出一种方法,按小时计算并发用户的数量 我使用了蛮力方法,根据所有行检查每个小时时段,看它是否符合条件(如果开始时间在该时段内,如果结束时间在该时段内,或者会话是否在该时段外开始和结束) 我还使用了一种自连接方法,这是我在stackoverflow上的许多其他类似讨论线程中发现的,但结果和我的蛮力方法有点不同 基本上,我正在尝试寻找是否有一种方法可以在不使用暴力的情况下准确地找到并发用户(在x条记录上循环y个小时)。这就是所谓的暴

我有会话开始时间、会话结束时间和持续时间(以小时为单位)。我正试图找出一种方法,按小时计算并发用户的数量

我使用了蛮力方法,根据所有行检查每个小时时段,看它是否符合条件(如果开始时间在该时段内,如果结束时间在该时段内,或者会话是否在该时段外开始和结束)

我还使用了一种自连接方法,这是我在stackoverflow上的许多其他类似讨论线程中发现的,但结果和我的蛮力方法有点不同


基本上,我正在尝试寻找是否有一种方法可以在不使用暴力的情况下准确地找到并发用户(在x条记录上循环y个小时)。

这就是所谓的暴力,但并不可怕

with sample as (
select timestamp('2020-01-01 05:50:00') as session_start_time,timestamp('2020-01-01 05:59:00') session_end_time union all
select timestamp('2020-01-01 04:51:00') as session_start_time,timestamp('2020-01-01 05:58:00') session_end_time union all
select timestamp('2020-01-01 03:52:00') as session_start_time,timestamp('2020-01-01 05:57:00') session_end_time union all
select timestamp('2020-01-01 02:53:00') as session_start_time,timestamp('2020-01-01 05:56:00') session_end_time union all
select timestamp('2020-01-01 01:54:00') as session_start_time,timestamp('2020-01-01 05:55:00') session_end_time union all
select timestamp('2020-01-01 05:55:00') as session_start_time,timestamp('2020-01-01 05:56:00') session_end_time 

), base as (
select 
session_start_time, session_end_time, row_number() over( order by session_start_time) ses_id
from sample

),
buckets as (
select timestamp_trunc(ts, hour) bucket  from 
unnest(GENERATE_TIMESTAMP_ARRAY((select TIMESTAMP_SUB(min(session_start_time), interval  1 hour)  from sample), 
(select TIMESTAMP_ADD(max(session_end_time), interval  1 hour)  from sample), INTERVAL 1 hour )) ts
 
)

select bucket, count(distinct if(buckets.bucket between base.session_start_time and base.session_end_time, ses_id,null))
from buckets 
cross join base  
group by 1

请提供样本数据和预期结果。