LeetCode题解
解题思路:
1.首先先求出每个用户首次订单表,将其命名为表t
(select customer_id,min(order_date) as order_date
from Delivery
group by customer_id)as t
2.与原表连接,求出在用户首次订单表中即时订单的数量的总和
select sum(order_date = customer_pref_delivery_date) from
t,Delivery
where t.customer_id = Delivery.customer_id and t.order_date = Delivery.order_date
3.求出每个用户首次订单的数量
select distinct(customer_id) from Delivery
4.计算得到最终结果
完整SQL代码:
select round(sum(if(t.order_date = customer_pref_delivery_date,1,0))*100/(select count(*) from
(select distinct customer_id from Delivery) t1),2) as immediate_percentage
from (
select customer_id,min(order_date) as order_date
from Delivery
group by customer_id
) t,Delivery
where t.customer_id = Delivery.customer_id and t.order_date = Delivery.order_date