Skip to content

Commit b47a505

Browse files
authored
MEDIUM
1 parent a56570f commit b47a505

File tree

1 file changed

+60
-0
lines changed

1 file changed

+60
-0
lines changed

1174. Immediate Food Delivery II.sql

+60
Original file line numberDiff line numberDiff line change
@@ -1,2 +1,62 @@
1+
-- Problem:
2+
3+
/*
4+
Table: Delivery
5+
6+
+-----------------------------+---------+
7+
| Column Name | Type |
8+
+-----------------------------+---------+
9+
| delivery_id | int |
10+
| customer_id | int |
11+
| order_date | date |
12+
| customer_pref_delivery_date | date |
13+
+-----------------------------+---------+
14+
delivery_id is the column of unique values of this table.
15+
The table holds information about food delivery to customers that make orders at some date and specify a preferred delivery date (on the same order date or after it).
16+
17+
18+
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.
19+
20+
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.
21+
22+
Write a solution to find the percentage of immediate orders in the first orders of all customers, rounded to 2 decimal places.
23+
24+
The result format is in the following example.
25+
26+
27+
28+
Example 1:
29+
30+
Input:
31+
Delivery table:
32+
+-------------+-------------+------------+-----------------------------+
33+
| delivery_id | customer_id | order_date | customer_pref_delivery_date |
34+
+-------------+-------------+------------+-----------------------------+
35+
| 1 | 1 | 2019-08-01 | 2019-08-02 |
36+
| 2 | 2 | 2019-08-02 | 2019-08-02 |
37+
| 3 | 1 | 2019-08-11 | 2019-08-12 |
38+
| 4 | 3 | 2019-08-24 | 2019-08-24 |
39+
| 5 | 3 | 2019-08-21 | 2019-08-22 |
40+
| 6 | 2 | 2019-08-11 | 2019-08-13 |
41+
| 7 | 4 | 2019-08-09 | 2019-08-09 |
42+
+-------------+-------------+------------+-----------------------------+
43+
Output:
44+
+----------------------+
45+
| immediate_percentage |
46+
+----------------------+
47+
| 50.00 |
48+
+----------------------+
49+
Explanation:
50+
The customer id 1 has a first order with delivery id 1 and it is scheduled.
51+
The customer id 2 has a first order with delivery id 2 and it is immediate.
52+
The customer id 3 has a first order with delivery id 5 and it is scheduled.
53+
The customer id 4 has a first order with delivery id 7 and it is immediate.
54+
Hence, half the customers have immediate first orders.
55+
*/
56+
57+
-------------------------------------------------------------------------------
58+
59+
-- Solution:
60+
161
SELECT ROUND(SUM(IF(order_date=customer_pref_delivery_date,1,0))/ COUNT(*) *100,2) AS immediate_percentage FROM Delivery
262
WHERE (customer_id,order_date) IN (SELECT customer_id, MIN(order_date) FROM Delivery GROUP BY customer_id)

0 commit comments

Comments
 (0)