题解 | #牛客直播各科目出勤率#
牛客直播各科目同时在线人数
http://www.nowcoder.com/practice/d69677e41f9a4bf3b3ed7a42573e9490
第一步,得到每个时间在线的人数,即 in_datetime就加1,out_datetime就减1,再union,注意要保留user_id字段,避免union把不同用户相同时间的数据去重(或union all也行) --表t1
第二步,用sum(diff) over(partition by course_id order by t,diff desc)计算截止到某一时间的总在线人数 --表t2
第三步,选择最大的人数max(num)
最终的sql
with t1 as(
select
user_id,course_id,course_name, in_datetime t, 1 diff
from
course_tb
join
attend_tb
using(course_id)
union
select
user_id,course_id,course_name, out_datetime t, -1 diff
from
course_tb
join
attend_tb
using(course_id)),
t2 as(select course_id,course_name,t,
sum(diff) over(partition by course_id order by t,diff desc) num
from t1
order by course_name)
select course_id,course_name,max(num) max_num
from t2
group by course_id,course_name
order by course_id