此题共包含两张表:

表1:tb_get_car_record

表2:tb_get_car_order

要解决的问题:

问题:请统计各个城市在2021年10月期间,单日中最大的同时等车人数。

注: 等车指从开始打车起,直到取消打车、取消等待或上车前的这段时间里用户的状态。 如果同一时刻有人停止等车,有人开始等车,等车人数记作先增加后减少。 结果按各城市最大等车人数升序排序,相同时按城市升序排序。

解题思路:

  1. 根据情况计算等车时间:
  • 打到车的,是从开始打车的event_time到start_time
  • 取消等待的,是从开始打车的event_time到finish_time,start_time为null
  • 取消打车的,是从开始打车的event_time到finish_time,order_time为null,start_time为null
  1. 将event_time开始打车设为1,start_time或者finish_time设为-1。根据1、2条得到两张表,union all获得所有所需数据
  2. 利用窗口函数获取各时点同时在线人数,以城市和时间为分组,累加同时在线的人数
  3. 找到最大同时在线人数,以及城市名
  4. 按等车人数升序排序,按城市升序排序
SELECT city, max(rank1) max_wait_uv
from(
    SELECT city, 
    sum(cnt) over(PARTITION by city, date(event_time) ORDER BY event_time, cnt desc) rank1
    from(
		SELECT order_id, city, 
               event_time,
               1 as cnt
		from tb_get_car_order left join tb_get_car_record using(order_id)

		union all

		SELECT order_id, city, 
               if(start_time is null, finish_time, start_time),
               -1 as cnt
		from tb_get_car_order left join tb_get_car_record using(order_id)
    	) t1
  	where DATE_FORMAT(event_time,'%Y%m') = '202110'
	) t2
GROUP by city
ORDER BY max_wait_uv, city