SQL Challenges-1: Return the shipping and delivery rates
SQL Challenges-1: Exercise-77 with Solution
From the following table write a query in SQL to return the shipped and delivered rate for each order. Return order_id, shipped percentage, and delivered percentage.
Table: orderdetails
Structure:
Field | Type | Null | Key | Default | Extra |
---|---|---|---|---|---|
order_id | int | NO | |||
order_status | varchar(30) | YES | |||
order_date | date | YES |
Data:
order_id | order_status | order_date |
---|---|---|
10001 | booked | 2008-08-15 |
10001 | shipped | 2008-08-16 |
10002 | booked | 2008-07-13 |
10002 | delivered | 2008-07-19 |
10003 | booked | 2008-08-15 |
10003 | delivered | 2008-08-18 |
10004 | booked | 2008-07-19 |
10004 | shipped | 2008-07-19 |
Sample Solution:
SQL Code(MySQL):
CREATE TABLE orderdetails (
order_id INT(5) NOT NULL,
order_status VARCHAR(30),
order_date DATE
);
insert into orderdetails values(10001,'booked','2008-08-15');
insert into orderdetails values(10001,'shipped','2008-08-16');
insert into orderdetails values(10002,'booked','2008-07-13');
insert into orderdetails values(10002,'delivered','2008-07-19');
insert into orderdetails values(10003,'booked','2008-08-15');
insert into orderdetails values(10003,'delivered','2008-08-18');
insert into orderdetails values(10004,'booked','2008-08-19');
insert into orderdetails values(10004,'shipped','2008-08-19');
WITH t1 AS (
SELECT
order_id,
SUM(CASE WHEN order_status = 'booked' THEN 1 ELSE 0 END) AS booked,
SUM(CASE WHEN order_status = 'shipped' THEN 1 ELSE 0 END) AS shipped,
SUM(CASE WHEN order_status = 'delivered' THEN 1 ELSE 0 END) AS delivered
FROM orderdetails
GROUP BY 1
ORDER BY 1)
SELECT
order_id,
1.0*shipped/booked AS shipped_perc,
1.0*delivered/booked AS delivered_perc
FROM t1;
Sample Output:
order_id|shipped_perc|delivered_perc| --------+------------+--------------+ 10001| 1.00000| 0.00000| 10002| 0.00000| 1.00000| 10003| 0.00000| 1.00000| 10004| 1.00000| 0.00000|
SQL Code Editor:
Contribute your code and comments through Disqus.
It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.
https://www.w3resource.com/sql-exercises/challenges-1/sql-challenges-1-exercise-77.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics