配送表: 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
-- 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 )
-- 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;
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,把最早时间的那条记录弄出来。