azarasi / LeetCode 1795. Rearrange Products Table

Created Thu, 07 Apr 2022 12:05:35 +0800 Modified Wed, 18 Sep 2024 14:00:22 +0000

Table: Products

Column NameType
product_idint
store1int
store2int
store3int

product_id is the primary key for this table. Each row in this table indicates the product’s price in 3 different stores: store1, store2, and store3. If the product is not available in a store, the price will be null in that store’s column.

Write an SQL query to rearrange the Products table so that each row has (product_id, store, price). If a product is not available in a store, do not include a row with that product_id and store combination in the result table.

Return the result table in any order.

The query result format is in the following example.

Example 1:

Input: Products table:

product_idstore1store2store3
095100105
170null80

Output:

product_idstoreprice
0store195
0store2100
0store3105
1store170
1store380

Explanation: Product 0 is available in all three stores with prices 95, 100, and 105 respectively. Product 1 is available in store1 with price 70 and store3 with price 80. The product is not available in store2.

SELECT product_id,
       'store1' store,
       store1   price
FROM Products
WHERE store1 IS NOT NULL
UNION ALL
SELECT product_id,
       'store2' store,
       store2   price
FROM Products
WHERE store2 IS NOT NULL
UNION ALL
SELECT product_id,
       'store3' store,
       store3   price
FROM Products
WHERE store3 IS NOT NULL;