Pivot rows to columns
MediumP2Coding
Table sales:
| Column | Type |
|---|---|
| product | text |
| quarter | int (1 to 4) |
| amount | int |
A product can have several rows for the same quarter. Turn quarters into columns: one row per product with the total sales of each quarter. A quarter without sales is 0.
Output columns: product, q1, q2, q3, q4.
Schema
CREATE TABLE sales ( product text NOT NULL, quarter int NOT NULL CHECK (quarter BETWEEN 1 AND 4), amount int NOT NULL );
Example 1
- Input
- sales: (pen, 1, 10), (pen, 1, 5), (pen, 3, 7)
- Output
- pen: q1 15, q2 0, q3 7, q4 0
Constraints
- PostgreSQL dialect.
Hints
Give it a real attempt first. Run shows which examples fail.
Saved automatically
PostgreSQL
Run checks the 3 visible tests, Submit all 5. ⌘Enter runs, ⌘⇧Enter submits.