SQL面试题挑战02:同时最大在线人数问题

目录

问题:

问题:如下为某直播平台各主播的开播及关播时间明细数据,现在需要计算出该平台最高峰期同时在线的主播人数。

powershell 复制代码
user_id     start_date              end_date
1001    2021-06-14 12:12:12     2021-06-14 18:12:12
1003    2021-06-14 13:12:12     2021-06-14 16:12:12
1004    2021-06-14 13:15:12     2021-06-14 20:12:12
1002    2021-06-14 15:12:12     2021-06-14 16:12:12
1005    2021-06-14 15:18:12     2021-06-14 20:12:12
1001    2021-06-14 20:12:12     2021-06-14 23:12:12
1006    2021-06-14 21:12:12     2021-06-14 23:15:12
1007    2021-06-14 22:12:12     2021-06-14 23:10:12

SQL解答:

这是非常经典的一个面试题,不管大厂小厂都有问到过。解题思路也比较固定:就是用1代表开播(此时用开播时间),-1代表关播(此时用关播时间),可以理解1代表主播开播加入增1,-1代表主播关播离开减1,然后开窗可以计算出到每个时间点时有多少主播同时在线,最后求最大值即可。

sql 复制代码
with tmp as
(
    select 1001 as user_id, '2021-06-14 12:12:12' as start_date , '2021-06-14 18:12:12' as end_date
    union all
    select 1003 as user_id, '2021-06-14 13:12:12' as start_date , '2021-06-14 16:12:12' as end_date
    union all
    select 1004 as user_id, '2021-06-14 13:15:12' as start_date , '2021-06-14 20:12:12' as end_date
    union all
    select 1002 as user_id, '2021-06-14 15:12:12' as start_date , '2021-06-14 16:12:12' as end_date
    union all
    select 1005 as user_id, '2021-06-14 15:18:12' as start_date , '2021-06-14 20:12:12' as end_date
    union all
    select 1001 as user_id, '2021-06-14 20:12:12' as start_date , '2021-06-14 23:12:12' as end_date
    union all
    select 1006 as user_id, '2021-06-14 21:12:12' as start_date , '2021-06-14 23:15:12' as end_date
    union all
    select 1007 as user_id, '2021-06-14 22:12:12' as start_date , '2021-06-14 23:10:12' as end_date
)
select
max(online_nums) as max_online_nums
from
(
    select
    user_id
    ,dt
    ,sum(flag) over(order by dt) as online_nums
    from
    (
        select
        user_id
        ,start_date as dt
        ,1 as flag  --开播记为1
        from tmp
        union all
        select
        user_id
        ,end_date as dt
        ,-1 as flag --关播记为-1
        from tmp
    )t1
)t1
;
相关推荐
⁤⁢初遇1 分钟前
MySQL---数据库基础
数据库
wolf犭良9 分钟前
27、Python 数据库操作入门(SQLite)从基础到实战精讲
数据库·python·sqlite
画扇落汗26 分钟前
Python 几种将数据插入到数据库的方法(单行插入、批量插入,SQL Server、MySQL,insert into)
数据库·python·sql·mysql
银河系的一束光28 分钟前
mysql的下载和安装2025.4.8
数据库·mysql
Full Stack Developme35 分钟前
SQL 查询中使用 IN 导致性能问题的解决方法
数据库·sql
神经星星1 小时前
【vLLM 学习】API 客户端
数据库·人工智能·机器学习
小光学长2 小时前
基于flask+vue框架的助贫公益募捐管理系统1i6pi(程序+源码+数据库+调试部署+开发环境)带论文文档1万字以上,文末可获取,系统界面在最后面。
数据库
XiaoLeisj2 小时前
【图书管理系统】深入解析基于 MyBatis 数据持久化操作:全栈开发图书管理系统:查询图书属性接口(注解实现)、修改图书属性接口(XML 实现)
xml·java·数据库·spring boot·sql·java-ee·mybatis
Alt.93 小时前
SpringMVC基础一(SpringMVC运行原理)
数据库·spring·mvc
薛晓刚4 小时前
OceanBase单机版保姆级安装
数据库