QuXiangjie / Study-Review

自己欠缺的还太多了,希望通过总结每天的学习内容,整理每天的思绪来丰富自己的知识库。我想成为一名优秀的金融数据分析师,并行发展技术与商业业务。博客内容为:数理统计、财务业务、Python(数据分析及可视化)、Excel(数据分析)、SQL、英文
0 stars 0 forks source link

1174. Immediate Food Delivery II #27

Open QuXiangjie opened 6 months ago

QuXiangjie commented 6 months ago

1174. Immediate Food Delivery II

My solution

-- Find the first orders of all customers
-- Calculate the immediate orders

WITH cte AS (
    SELECT 
        *,
        DENSE_RANK() OVER (PARTITION BY customer_id ORDER BY order_date) AS dense_ranking
    FROM 
        Delivery
), 
first_cte AS (
    SELECT *
    FROM cte
    WHERE dense_ranking = 1
),
immediate_cte AS (
    SELECT *
    FROM first_cte
    WHERE order_date = customer_pref_delivery_date
)
SELECT 
    ROUND((SELECT COUNT(*) FROM immediate_cte) / (SELECT COUNT(*) FROM first_cte) * 100, 2) AS immediate_percentage;

Just notice that the MySQL doesn't support the numeric function

Other solution

Select 
    round(avg(order_date = customer_pref_delivery_date)*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
);