Description
Write a SQL query to pivot monthly revenue data. Return id with a column for each month (Jan, Feb, Mar). Months with no data should show as empty/NULL. **Output columns (in order):** id, Jan_revenue, Feb_revenue, Mar_revenue
department| Column | Type |
|---|---|
| id | INT |
| revenue | INT |
| month | TEXT |
Examples
CREATE TABLE department (id INT, revenue INT, month TEXT); INSERT INTO department VALUES (1, 1000, 'Jan'), (1, 2000, 'Feb');1|1000|2000Department 1 had revenue of 1000 in January and 2000 in February. The pivot creates columns for each month.
CREATE TABLE department (id INT, revenue INT, month TEXT); INSERT INTO department VALUES (3, 5000, 'Jan'), (3, 3200, 'Mar'), (4, 2800, 'Feb'), (4, 4100, 'Mar');3|5000||3200
4||2800|4100Department 3: Jan=5000, Feb=NULL (no data), Mar=3200. Department 4: Jan=NULL, Feb=2800, Mar=4100. Use CASE WHEN month='Jan' THEN revenue END with GROUP BY id to pivot rows into columns, producing NULL for missing months.
CREATE TABLE department (id INT, revenue INT, month TEXT); INSERT INTO department VALUES (5, 7500, 'Jan'), (5, 6800, 'Feb'), (5, 8200, 'Mar'), (6, 4200, 'Jan'), (6, 3900, 'Feb'), (6, 5100, 'Mar');5|7500|6800|8200
6|4200|3900|5100Department 5 has revenue in all three months: 7500 (Jan), 6800 (Feb), 8200 (Mar). Department 6 also has complete data: 4200 (Jan), 3900 (Feb), 5100 (Mar). The pivot transforms rows into columns, creating one row per department with monthly revenue as separate columns.
Constraints
- •
Use CASE statements or pivot