Table Schema
Inspect
Table
| Column | Type | Description |
|---|---|---|
| order_id | integer | Order identifier. |
| product_id | integer | Product identifier. |
| is_returned | integer | 1 if the product was returned, otherwise 0. |
Find the product with the highest return rate.
Table Schema
| Column | Type | Description |
|---|---|---|
| order_id | integer | Order identifier. |
| product_id | integer | Product identifier. |
| is_returned | integer | 1 if the product was returned, otherwise 0. |
Sample Data
| order_id | product_id | is_returned |
|---|---|---|
| 1 | 10 | 1 |
| 2 | 10 | 0 |
| 3 | 20 | 1 |
| 4 | 20 | 1 |
| 5 | 30 | 0 |
| 6 | 30 | 0 |
| product_id | return_rate |
|---|---|
| 20 | 100 |
SQL Editor
| product_id | return_rate |
|---|---|
| 20 | 100 |
Hints
Solution
Solution is locked until you decide to reveal it. Try the editor first, then open this when you want the reference answer.
WITH product_returns AS (
SELECT
product_id,
ROUND(AVG(is_returned) * 100, 0) AS return_rate
FROM orders
GROUP BY product_id
),
ranked_products AS (
SELECT
product_id,
return_rate,
DENSE_RANK() OVER (ORDER BY return_rate DESC) AS return_rank
FROM product_returns
)
SELECT
product_id,
return_rate
FROM ranked_products
WHERE return_rank = 1
ORDER BY product_id;
Explanation
Calculate the return percentage for each product.
Rank products by that percentage from highest to lowest.
Keep the top-ranked product or products if there is a tie.
Related Questions