|
| 1 | +/* |
| 2 | +Question 3564. Seasonal Sales Analysis |
| 3 | +Link: https://leetcode.com/problems/seasonal-sales-analysis/description/?envType=problem-list-v2&envId=database |
| 4 | +
|
| 5 | +Table: sales |
| 6 | +
|
| 7 | ++---------------+---------+ |
| 8 | +| Column Name | Type | |
| 9 | ++---------------+---------+ |
| 10 | +| sale_id | int | |
| 11 | +| product_id | int | |
| 12 | +| sale_date | date | |
| 13 | +| quantity | int | |
| 14 | +| price | decimal | |
| 15 | ++---------------+---------+ |
| 16 | +sale_id is the unique identifier for this table. |
| 17 | +Each row contains information about a product sale including the product_id, date of sale, quantity sold, and price per unit. |
| 18 | +Table: products |
| 19 | +
|
| 20 | ++---------------+---------+ |
| 21 | +| Column Name | Type | |
| 22 | ++---------------+---------+ |
| 23 | +| product_id | int | |
| 24 | +| product_name | varchar | |
| 25 | +| category | varchar | |
| 26 | ++---------------+---------+ |
| 27 | +product_id is the unique identifier for this table. |
| 28 | +Each row contains information about a product including its name and category. |
| 29 | +Write a solution to find the most popular product category for each season. The seasons are defined as: |
| 30 | +
|
| 31 | +Winter: December, January, February |
| 32 | +Spring: March, April, May |
| 33 | +Summer: June, July, August |
| 34 | +Fall: September, October, November |
| 35 | +The popularity of a category is determined by the total quantity sold in that season. If there is a tie, select the category with the highest total revenue (quantity × price). |
| 36 | +
|
| 37 | +Return the result table ordered by season in ascending order. |
| 38 | +*/ |
| 39 | + |
| 40 | +WITH stats AS ( |
| 41 | + SELECT |
| 42 | + p.category, |
| 43 | + (CASE |
| 44 | + WHEN EXTRACT(MONTH FROM s.sale_date) BETWEEN 3 AND 5 |
| 45 | + THEN 'Spring' |
| 46 | + WHEN EXTRACT(MONTH FROM s.sale_date) BETWEEN 6 AND 8 |
| 47 | + THEN 'Summer' |
| 48 | + WHEN EXTRACT(MONTH FROM s.sale_date) BETWEEN 9 AND 11 |
| 49 | + THEN 'Fall' |
| 50 | + ELSE 'Winter' |
| 51 | + END) AS season, |
| 52 | + SUM(s.quantity) AS total_quantity, |
| 53 | + SUM(s.quantity * s.price) AS total_revenue |
| 54 | + FROM sales AS s |
| 55 | + LEFT JOIN |
| 56 | + products AS p |
| 57 | + ON s.product_id = p.product_id |
| 58 | + GROUP BY s.season, p.category |
| 59 | +) |
| 60 | + |
| 61 | +SELECT |
| 62 | + s.season, |
| 63 | + s.category, |
| 64 | + s.total_quantity, |
| 65 | + s.total_revenue |
| 66 | +FROM ( |
| 67 | + SELECT |
| 68 | + s1.season, |
| 69 | + s1.category, |
| 70 | + s1.total_quantity, |
| 71 | + s1.total_revenue, |
| 72 | + RANK() OVER(PARTITION BY s1.season ORDER BY s1.total_quantity DESC, s1.total_revenue DESC) AS rank |
| 73 | + FROM stats AS s1 |
| 74 | +) AS s |
| 75 | +WHERE s.rank = 1 |
| 76 | +ORDER BY s.season ASC |
0 commit comments