SQL题解之使用union和sum解决同时在线人数问题

现有各直播间的用户访问记录表(live_events)如下,表中每行数据表达的信息为,一个用户何时进入了一个直播间,又在何时离开了该直播间。

user_id (用户id) live_id (直播间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 <int> (直播id) max_user_count <int> (最大人数)
1 4
2 3
3 2

--- 1.计算逻辑

对于同时在线人数问题,可以把数据进行处理后,然后将出入时间变成一个字段,同时打上标记为1或-1表示进入离开直播间,同时使用sum()函数累加这个字段,最大值为峰值人数

-- 1.对数据进行处理

in_datetime dt, out_datetime dt 设置为时间日期字段,同时打上进入出去标记1,-1

-- 2.union成一个字段
sql 复制代码
     select
        live_id,
        in_datetime dt,
        1 flag
    from live_events
    union all
    select 
        live_id,
        out_datetime,
        -1
    from live_events
-- 3.使用sum over()开窗函数累加人数

按照直播间分区并按照时间进行排序

sql 复制代码
 sum(flag) over(partition by live_id order by dt asc) as ct
--4. 求最大的人数

按照直播间分组,求最大人数

sql 复制代码
 max(ct) as  max_user_count
group by live_id
-- 5.最终SQL
sql 复制代码
select
	live_id,
    max(ct) as  max_user_count
from 
(
  select
      live_id,
      dt,
      sum(flag) over(partition by live_id order by dt asc) as ct
  from 
  (
    select
        live_id,
        in_datetime dt,
        1 flag
    from live_events
    union all
    select 
        live_id,
        out_datetime,
        -1
    from live_events
  )t1
)t2
group by live_id
相关推荐
漂着的圆木1 天前
Agent 功能参与度:Copilot 怎么算
sql·数据分析·agent·githubcopilot·度量
旺仔不是程序员2 天前
LIMIT 1:PostgreSQL 只取一行的高效查询姿势
数据库·后端·sql
知识的搬运工旺仔2 天前
唯一索引与 NULL 值:PostgreSQL 主键约束与 NULLS NOT DISTINCT
数据库·后端·sql·postgresql
想念是会呼吸的鱼3 天前
【ClickHouse 常用 SQL 语句整理】
sql·clickhouse
想念是会呼吸的鱼3 天前
MySQL 常用语法整理
sql·mysql
SelectDB技术团队3 天前
StarRocks 迁移至 Apache Doris 完整指南:三步完成结构、数据与业务平滑切换
数据库·人工智能·sql·clickhouse·apache doris·selectdb·湖仓架构升级
imDwAaY3 天前
MySQL MVCC 详解:原理、版本链、Read View 与可见性判断
数据库·sql·mysql
bbq粉刷匠3 天前
触发器(下):事务与锁、binlog 一致性与替代方案
sql