题解 | #各城市最大同时等车人数#

各城市最大同时等车人数

http://www.nowcoder.com/practice/f301eccab83c42ab8dab80f28a1eef98

总代码

with t1 as (
    SELECT city,type
        ,rank() over(partition by city order by event_time,type desc) as 'rnk'
    from (
        SELECT city,event_time,1 as 'type' from tb_get_car_record
        union all 
        SELECT city
            ,( case when start_time is null then finish_time
                    when order_id is null then end_time
                    else start_time end
            ) as 'event_time'
            ,-1 as 'type'
        from tb_get_car_record as A
        left join tb_get_car_order as B
        using(order_id)
    ) as temp
    where date_format(event_time,'%Y-%m') = '2021-10'
)
select city 
    ,max(num) as 'max_wait_uv'
from (
    select city,type
        ,( select sum(type)
          from t1 as B where B.city = A.city 
          and B.rnk <= A.rnk
        ) as 'num'
    from t1 as A
) as t2
group by city order by max_wait_uv

思路分析

1.构造临时表

  1. 遇到同时在线问题,基本都是把开始时间和结束时间单独取出后使用union all进行合并(union 会去重)
  2. 并新增列(如命名为type)分别赋值为1,-1以区分人数加减
  3. 若要求如【如果同一时刻有人停止等车,有人开始等车,等车人数记作先增加后减少】,则需在新增一列排序,以方便计算人数(如果后面计算人数只是用时间来比较而不是用序号,遇到同个时间点有加有减则会计算错误)

本题中的开始时间比较容易:为用户开始打车时间即event_time

结束时间

  • 若司机接单后取消订单则为,finish_time
  • 若用户自己取消则为,end_time
  • 若司机成功接单则为,start_time

代码及该部分结果(图中为了便于理解rnk作用还select了event_time)如下

with t1 as (
    SELECT city,type
        ,rank() over(partition by city order by event_time,type desc) as 'rnk'
    from (
        SELECT city,event_time,1 as 'type' from tb_get_car_record
        union all 
        SELECT city
            ,( case when start_time is null then finish_time
                    when order_id is null then end_time
                    else start_time end
            ) as 'event_time'
            ,-1 as 'type'
        from tb_get_car_record as A
        left join tb_get_car_order as B
        using(order_id)
    ) as temp
    where date_format(event_time,'%Y-%m') = '2021-10'
)
select * from t1

alt

2.计算人数

有了临时表后接下来就容易了,只需要进行分组计算(把小于当前行的序号的type进行累计求和)即可

select city,max(num) as 'max_wait_uv'
from (
    select city,type
        ,( select sum(type) from t1 as B 
          where B.city = A.city and B.rnk <= A.rnk
        ) as 'num'
    from t1 as A
) as t2
group by city order by max_wait_uv
全部评论

相关推荐

就前几天旅游的时候,打开抖音就经常刷到这类视频:以前是高学历学生、老师、主持人,现在做着团播、擦边主播的工作,以及那些经过精心包装的“职业转型”故事——从铺天盖地的VLOG到所谓的“04年夜场工作日记”,这些内容在初中升学、高考放榜等关键时间节点持续发酵。可以说非常直接且精准地在潜移默化地影响着心智尚未成熟的青少年,使其对特殊行业逐渐脱敏。那我就想问了:某些传播公司、平台运营者甚至某些夜场的老板,你们究竟在传递怎样的价值观?点开那些视频,评论区里也是呈现明显的两极分化:一种是​​经济下行论​​:“现在就业市场已经艰难到这种程度了吗?”​​一种是事实反驳派​​:这些创作者往往拥有名校背景,从事着...
牛客刘北:被环境教育的,为了能拿到足够的钱养活自己,不甘心也得甘心,现在的短视频传播的思想的确很扭曲,但是很明显,互联网玩上一年你就能全款提A6,但你全心全意不吃不喝工作一年未必能提A6,但是在高考中考出现这个的确很扭曲,在向大家传播“不上学,玩互联网也可以轻松年入百万”,不是人变了,是社会在变
预测一下26届秋招形势
点赞 评论 收藏
分享
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务