Pivot Store Sales by Quarter
Problem
Table: `StoreSales`
```text
+----------+--------+---------+
| Column | Type | Notes |
+----------+--------+---------+
| store_id | int | |
| sales | int | |
| quarter | varchar| Q1..Q4 |
+----------+--------+---------+
(store_id, quarter) is the primary key. Each row is one store's sales in one
quarter.
```
Reshape the table so there is one row per store and a separate sales column
for each of the four quarters. The output columns must be exactly: `store_id`,
`Q1_sales`, `Q2_sales`, `Q3_sales`, `Q4_sales`. If a store has no row for a
quarter, that quarter's value should be NULL.
**Example**
```text
StoreSales:
+----------+-------+---------+
| store_id | sales | quarter |
+----------+-------+---------+
| 1 | 100 | Q1 |
| 1 | 200 | Q2 |
| 2 | 50 | Q1 |
+----------+-------+---------+
Output:
+----------+----------+----------+----------+----------+
| store_id | Q1_sales | Q2_sales | Q3_sales | Q4_sales |
+----------+----------+----------+----------+----------+
| 1 | 100 | 200 | NULL | NULL |
| 2 | 50 | NULL | NULL | NULL |
+----------+----------+----------+----------+----------+
```
Tables
Example rows — the live problem includes the full dataset.
| store_id | sales | quarter |
|---|---|---|
| 1 | 100 | Q1 |
| 1 | 200 | Q2 |
| 2 | 50 | Q1 |
Expected output
Your answer should return 2 rows with the columns store_id, Q1_sales, Q2_sales, Q3_sales, Q4_sales.
Starter code (SQL)
SELECT *
FROM StoreSales;Solve this SQL question free
Write SQL and run it instantly in your browser — even on your phone. No signup needed to try.
Solution & explanation
Create a free account to unlock the optimal solution, a step-by-step explanation, and the hidden test cases that grade your answer.
Sign up free to unlock