2024-01-25 力扣高频SQL50题目1174. 即时食物配送

题目如下:

配送表: Delivery

+-----------------------------+---------+
| Column Name                 | Type    |
+-----------------------------+---------+
| delivery_id                 | int     |
| customer_id                 | int     |
| order_date                  | date    |
| customer_pref_delivery_date | date    |
+-----------------------------+---------+
delivery_id 是该表中具有唯一值的列。
该表保存着顾客的食物配送信息,顾客在某个日期下了订单,并指定了一个期望的配送日期(和下单日期相同或者在那之后)。

如果顾客期望的配送日期和下单日期相同,则该订单称为 「即时订单」,否则称为「计划订单」。

首次订单」是顾客最早创建的订单。我们保证一个顾客只会有一个「首次订单」。

编写解决方案以获取即时订单在所有用户的首次订单中的比例。保留两位小数。

------

这个题目还是很有意思的。

一开始,我以为即时订单总量/所有用户首次订单数总量。

-- 不对

-- select round((sum(if(order_date=customer_pref_delivery_date,1,0))/count(distinct customer_id )),4)*100 as immediate_percentage  from Delivery

-- 不对

-- select round((sum(if(order_date=customer_pref_delivery_date,1,0))/(select distinct count( customer_id )from Delivery ))*100,2) as immediate_percentage  from Delivery

-- 不对

-- select round((sum(if(order_date=customer_pref_delivery_date,1,0))/(select  COUNT(DISTINCT customer_id) from Delivery ))*100,2) as immediate_percentage  from Delivery

-- 我看了下其他人答案,发现自己理解错了。

"即时订单在所有用户的首次订单中的比例"。

应该是 所有用户的首次订单中的即时订单总数 / 所有用户的首次订单量

所以,需要框定范围,首次订单

-- 不对

-- select round((sum(if(order_date=customer_pref_delivery_date,1,0))/(select  COUNT(DISTINCT customer_id) from Delivery  ))*100,2) as immediate_percentage  from Delivery group by customer_id


正确的写法:

-- 没用rownumber的解法

-- select round((sum(if(order_date=customer_pref_delivery_date,1,0))/(select  COUNT(DISTINCT customer_id) from Delivery  ))*100,2) as immediate_percentage  from Delivery where (customer_id, order_date) in (

select customer_id, min(order_date)

from delivery

group by customer_id )

-- 用rownumber的解法

-- SELECT round((sum(if(order_date=customer_pref_delivery_date,1,0))/(SELECT COUNT(DISTINCT customer_id) FROM Delivery))*100, 2) AS immediate_percentage

-- FROM

 (SELECT *, ROW_NUMBER() OVER(PARTITION BY customer_id ORDER BY order_date) AS rn   FROM Delivery) AS subquery WHERE rn = 1;

--用rownumber的解法 + count(*)

SELECT round((sum(if(order_date=customer_pref_delivery_date,1,0))/count(*))*100, 2) AS immediate_percentage

FROM

  (SELECT *,

  ROW_NUMBER() OVER(PARTITION BY customer_id ORDER BY order_date) AS rn

  FROM Delivery) AS subquery

WHERE rn = 1;

最后这个是比较好。直接将【首次订单】作为from来源的数据,count(*)因为where已经把条件框定了。

如何框定的?用row_number,把最早时间的那条记录弄出来。

你可能感兴趣的:(数据库,sql)