Unpivot Quarterly Sales
Role: Data Scientist
Category: Data Manipulation (SQL/Python)
Difficulty: easy
Interview Round: Other
Unpivot `quarterly_sales` into one row per product per quarter with columns `product_id`, `quarter` (`'Q1'`, `'Q2'`, `'Q3'`, `'Q4'`) and `sales`. Order by `product_id`, then `quarter`.
```hint One row becomes four
Each product row has to turn into four output rows, and each of those rows must know which sales column it reads from.
```
### Input Table(s)
`quarterly_sales`
| Column | Type | Meaning |
|---|---|---|
| product_id | INT | Product identifier |
| q1_sales | DECIMAL(10,2) | Sales in quarter 1, may be NULL |
| q2_sales | DECIMAL(10,2) | Sales in quarter 2, may be NULL |
| q3_sales | DECIMAL(10,2) | Sales in quarter 3, may be NULL |
| q4_sales | DECIMAL(10,2) | Sales in quarter 4, may be NULL |
Key: each `product_id` appears in exactly one row.
### Output Contract
| Column | Meaning |
|---|---|
| product_id | The product |
| quarter | One of the text labels `'Q1'`, `'Q2'`, `'Q3'`, `'Q4'` |
| sales | The value of the matching quarter column, unchanged (NULL stays NULL) |
Sort by `product_id` ascending, then `quarter` ascending. The pair (`product_id`, `quarter`) is unique. Sales keep their stored two decimal places, with no rounding.
### Example
`quarterly_sales`
| product_id | q1_sales | q2_sales | q3_sales | q4_sales |
|---|---|---|---|---|
| 10 | 500.00 | NULL | 300.00 | NULL |
Expected output:
| product_id | quarter | sales |
|---|---|---|
| 10 | Q1 | 500.00 |
| 10 | Q2 | NULL |
| 10 | Q3 | 300.00 |
| 10 | Q4 | NULL |
A single product with NULL sales in Q2 and Q4 still produces all 4 rows. The missing quarters carry NULL in the `sales` column.
### Constraints and Clarifications
- There are at most 10,000 products.
- Sales values are non-negative decimals with up to 2 places, or NULL.
- Every product yields exactly 4 rows, even when some or all of its quarter values are NULL. Do not replace NULL with 0.
Overview: Write a SQL query that reshapes a wide table of quarterly product sales into one row per product per quarter. It tests unpivoting columns into rows, keeping NULL quarters in the output, and producing a deterministic sort order.