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

各城市最大同时等车人数

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

WITH t as(
SELECT event_time AS wait_time,	
1 AS flag,city
FROM tb_get_car_record AS gcr
JOIN tb_get_car_order AS gco
ON gcr.order_id = gco.order_id
UNION ALL
SELECT (CASE 
WHEN gcr.order_id IS NULL THEN end_time
WHEN start_time IS NULL THEN finish_time
ELSE start_time
END)AS wait_time,	
-1 AS flag,city
FROM tb_get_car_record AS gcr
JOIN tb_get_car_order AS gco
ON gcr.order_id = gco.order_id
),
t1 as(
SELECT city,
SUM(flag)OVER(PARTITION BY city,DATE(wait_time) ORDER BY wait_time ASC,flag DESC) AS wait_nv 
FROM t
WHERE YEAR(wait_time) = 2021 AND MONTH(wait_time) = 10
)


SELECT city,MAX(wait_nv) AS max_wait_uv 
FROM t1
GROUP BY city
ORDER BY max_wait_uv ASC,city ASC;

需要是UNION ALL,因为如果存在重复记录,比如有两个用户同时打车。

如果不采用UNION ALL,而是采用UNION,需要在with查询中加入uid字段,这样保证两条记录不一样,从而不会被删去。

全部评论

相关推荐

头像
11-21 11:39
四川大学 Java
是红鸢啊:忘了还没结束,还有字节的5k 违约金
点赞 评论 收藏
分享
hso_:哈哈哈哈哈哈我没offer一样在同一道题开喷了
投递深圳同为数码等公司10个岗位
点赞 评论 收藏
分享
昨天 11:21
门头沟学院 Java
总包48.5w,意想不到的价格
无情咸鱼王的秋招日记之薛定谔的Offer:R
点赞 评论 收藏
分享
评论
点赞
收藏
分享
牛客网
牛客企业服务