题解|14. 抖音直播间各个时间段的在线人数
抖音直播间各个时间段的在线人数
明确题意:
统计7:00-9:00(早通勤)、18:00-20:00(晚通勤)、12:00-14:00(午休)、22:00-24:00(临睡)各个时间段的在线人数。
问题拆解:
- 标记每条记录是否在4个时段内在线。知识点:
if(in_time <= "23:59:59" and out_time > "22:00:00", user_id, null)
- 统计每个时段在线用户数。count(distinct)
代码实现:
select count(distinct if(in_time < "09:00:00" and out_time > "07:00:00", user_id, null)) as `早通勤`,
count(distinct if(in_time < "20:00:00" and out_time > "18:00:00", user_id, null)) as `晚通勤`,
count(distinct if(in_time < "14:00:00" and out_time > "12:00:00", user_id, null)) as `午休`,
count(distinct if(in_time <= "23:59:59" and out_time > "22:00:00", user_id, null)) as `临睡`
from user_view_tb