+-----------------------------+---------+
|Column Name |Type|+-----------------------------+---------+
| delivery_id | int || customer_id | int || order_date | date || customer_pref_delivery_date | date |+-----------------------------+---------+
delivery_id is the columnofuniquevaluesof this table.
The table holds information about food delivery to customers that make orders atsome date and specify a preferred delivery date (on the same order date orafter it).
If the customer’s preferred delivery date is the same as the order date, then the order is called immediate; otherwise, it is called scheduled.
The first order of a customer is the order with the earliest order date that the customer made. It is guaranteed that a customer has precisely one first order.
Write a solution to find the percentage of immediate orders in the first orders of all customers, rounded to 2 decimal places.
Input:
Delivery table:
+-------------+-------------+------------+-----------------------------+
| delivery_id | customer_id | order_date | customer_pref_delivery_date |+-------------+-------------+------------+-----------------------------+
|1|1|2019-08-01|2019-08-02||2|2|2019-08-02|2019-08-02||3|1|2019-08-11|2019-08-12||4|3|2019-08-24|2019-08-24||5|3|2019-08-21|2019-08-22||6|2|2019-08-11|2019-08-13||7|4|2019-08-09|2019-08-09|+-------------+-------------+------------+-----------------------------+
Output:
+----------------------+
| immediate_percentage |+----------------------+
|50.00|+----------------------+
Explanation:
The customer id 1 has a firstorderwith delivery id 1and it is scheduled.
The customer id 2 has a firstorderwith delivery id 2and it isimmediate.
The customer id 3 has a firstorderwith delivery id 5and it is scheduled.
The customer id 4 has a firstorderwith delivery id 7and it isimmediate.
Hence, half the customers have immediatefirst orders.
We want to find, for each customer, their first order and check if it was immediate (order date equals preferred delivery date). Then, we calculate the percentage of such immediate first orders among all customers.
SELECT ROUND(
100.0*SUM(order_date = customer_pref_delivery_date) /COUNT(*),
2 ) AS immediate_percentage
FROM (
SELECT*, ROW_NUMBER() OVER (PARTITION BY customer_id ORDERBY order_date) AS rn
FROM Delivery
) t
WHERE rn =1;
1
2
3
4
5
6
7
8
9
10
SELECT ROUND(
100.0*SUM(CASEWHEN order_date = customer_pref_delivery_date THEN1ELSE0END) /COUNT(*),
2 ) AS immediate_percentage
FROM (
SELECT*, ROW_NUMBER() OVER (PARTITION BY customer_id ORDERBY order_date) AS rn
FROM Delivery
) t
WHERE rn =1;