Skip to content
Onsite

Unpivot columns into rows

MediumP3Coding

Table products:

ColumnType
idint (primary key)
store1int (NULL if not sold there)
store2int
store3int

Turn the three price columns into rows: one row per product and store where the price is not NULL. A price of 0 is a real price and stays.

Output columns: product_id, store ('store1', 'store2' or 'store3'), price.

Schema

CREATE TABLE products (
  id int PRIMARY KEY,
  store1 int,
  store2 int,
  store3 int
);

Example 1

Input
products: (1, 10, NULL, 30)
Output
(1, store1, 10), (1, store3, 30)

Constraints

  • PostgreSQL dialect.

Hints

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