前言
就一直向前走吧,沿途的花终将绽放~
题目:主播同时在线人数问题
如下为某直播平台主播开播及关播时间,根据该数据计算出平台最高峰同时在线的主播人数。
id          stt                 edt
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建表:
数据准备:

create table t16(id            int,stt           string,edt           string
)row format delimited fields terminated by '\t';插入数据:
load data local inpath '/opt/data/t16.txt' overwrite into table  t16;需求实现:
select max(c2)
from (select c1,flag,sum(flag) over(order by c1,id) c2from(select id,stt as c1,1 flag from t16union allselect id,edt as c1,-1 flag from t16)t1)t2;hsql语句分析:
内部查询(子查询t1):
- 从
t16表中选择了两列,并为它们分别赋予了别名c1和flag。- 对于
t16表中的每一行,如果它是stt列,则flag为1,并作为c1的值;如果它是edt列,则flag为-1,并作为c1的值。这实际上是通过UNION ALL将两个结果集合并成一个,其中一个结果集包含stt作为正值,另一个结果集包含edt作为负值。
中间查询(子查询t2):
- 使用了窗口函数
SUM(flag) OVER (ORDER BY c1, id)来计算累积和。这个累积和是根据c1(即原始的stt或edt)和id的顺序来计算的。- 结果集中的每一行都包含
c1、flag和累积和c2。
外部查询:
- 从中间查询
t2中选择累积和c2的最大值。
结果输出:
