Pivot monthly department revenue into one column per month
Company: Instacart
Role: Data Scientist
Category: Data Manipulation (SQL/Python)
Difficulty: easy
Interview Round: Other
The `Department` table stores one row per department per month. Pivot it into one row per `id` with 13 columns: `id`, then `Jan_Revenue`, `Feb_Revenue`, ..., `Dec_Revenue` (all 12 months in calendar order). A month without a row for that department is `NULL`. Order the result by `id`.
```hint Where to start
Every output row comes from the rows of one `id`. Think about how a single aggregate can be made to look only at the rows of one month.
```
### Input Table(s)
`Department`
| Column | Type | Meaning |
|---|---|---|
| id | INT | Department id |
| revenue | INT | Revenue of that department in that month (can be NULL) |
| month | VARCHAR(3) | Three-letter month abbreviation |
Primary key: `(id, month)`.
### Output Contract
- Exactly 13 columns, in this order: `id`, `Jan_Revenue`, `Feb_Revenue`, `Mar_Revenue`, `Apr_Revenue`, `May_Revenue`, `Jun_Revenue`, `Jul_Revenue`, `Aug_Revenue`, `Sep_Revenue`, `Oct_Revenue`, `Nov_Revenue`, `Dec_Revenue`. The column names are case-sensitive.
- One row per distinct `id` that appears in `Department`.
- Ordered by `id` ascending.
- Revenue values are returned as stored, with no rounding.
### Example
Input `Department`:
| id | revenue | month |
|---|---|---|
| 1 | 8000 | Jan |
| 2 | 9000 | Jan |
| 3 | 10000 | Feb |
| 1 | 7000 | Feb |
| 1 | 6000 | Mar |
| 2 | NULL | Dec |
Expected result:
| id | Jan_Revenue | Feb_Revenue | Mar_Revenue | Apr_Revenue | May_Revenue | Jun_Revenue | Jul_Revenue | Aug_Revenue | Sep_Revenue | Oct_Revenue | Nov_Revenue | Dec_Revenue |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
| 1 | 8000 | 7000 | 6000 | NULL | NULL | NULL | NULL | NULL | NULL | NULL | NULL | NULL |
| 2 | 9000 | NULL | NULL | NULL | NULL | NULL | NULL | NULL | NULL | NULL | NULL | NULL |
| 3 | NULL | 10000 | NULL | NULL | NULL | NULL | NULL | NULL | NULL | NULL | NULL | NULL |
Department 1 has rows for January through March only, so the other nine months are NULL. Department 2 has a December row, but its revenue is NULL, so `Dec_Revenue` is NULL as well.
### Constraints and Clarifications
- `(id, month)` is the composite primary key, so each department has at most one row per month.
- `month` is always one of `Jan`, `Feb`, `Mar`, `Apr`, `May`, `Jun`, `Jul`, `Aug`, `Sep`, `Oct`, `Nov`, `Dec`, spelled exactly like that.
- `revenue` can be NULL. A month whose row has NULL revenue shows NULL, the same as a month with no row.
- Departments with no rows at all do not appear in the output.
- The table has at most 10,000 rows.
Overview: Pivot a table of monthly department revenue rows into one row per department with twelve calendar-ordered month columns, leaving missing months as NULL. It tests conditional aggregation with CASE inside an aggregate, GROUP BY, NULL handling and exact column naming in PostgreSQL.