Skip to content
Onsite

Pivot rows to columns

MediumP2Coding

Table sales:

ColumnType
producttext
quarterint (1 to 4)
amountint

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

PostgreSQL
Run checks the 3 visible tests, Submit all 5.