84. Reshape Products Data
Imagine you're managing a multi-store inventory system where product pricing is tracked per store. Currently, the pricing data is stored in wide format (each store in a separate column). To generate reports or feed into dashboards, the data must be converted to a particular format.
You are given a Products table:
āāāāāāāāāāāāāāā¦āāāāāāāāāāā ā Column Name ā Type ā ā āāāāāāāāāāāāāā¬āāāāāāāāāā⣠ā product_id ā int ā āāāāāāāāāāāāāāā¼āāāāāāāāāāā ā store1 ā int ā āāāāāāāāāāāāāāā¼āāāāāāāāāāā ā store2 ā int ā āāāāāāāāāāāāāāā¼āāāāāāāāāāā ā store3 ā int ā āāāāāāāāāāāāāāā©āāāāāāāāāāā
- product_id: Unique ID of the product (Primary Key)
- store1: Price of the product in Store 1 (nullable)
- store2: Price of the product in Store 2 (nullable)
- store3: Price of the product in Store 3 (nullable)
- A price of NULL means the product is not available in that store.
Write a query to transform the Products table so that each row contains the product_id, the store name, and its corresponding price. If a product is not available in a store (i.e., the price is NULL), exclude that row from the result.
Return the result ordered by product_id, store, and price in ascending order.
Example 1:
Example:
Input:
Products table:
āāāāāāāāāāāāāā¦āāāāāāāāā¦āāāāāāāāā¦āāāāāāāāā ā product_id ā store1 ā store2 ā store3 ā ā āāāāāāāāāāāāā¬āāāāāāāāā¬āāāāāāāāā¬āāāāāāāā⣠ā 0 ā 95 ā 100 ā 105 ā āāāāāāāāāāāāāā¼āāāāāāāāā¼āāāāāāāāā¼āāāāāāāāā ā 1 ā 70 ā NULL ā 80 ā āāāāāāāāāāāāāā©āāāāāāāāā©āāāāāāāāā©āāāāāāāāā
Expected Output:
āāāāāāāāāāāāāā¦āāāāāāāāā¦āāāāāāāā ā product_id ā store ā price ā ā āāāāāāāāāāāāā¬āāāāāāāāā¬āāāāāāā⣠ā 0 ā store1 ā 95 ā āāāāāāāāāāāāāā¼āāāāāāāāā¼āāāāāāāā ā 0 ā store2 ā 100 ā āāāāāāāāāāāāāā¼āāāāāāāāā¼āāāāāāāā ā 0 ā store3 ā 105 ā āāāāāāāāāāāāāā¼āāāāāāāāā¼āāāāāāāā ā 1 ā store1 ā 70 ā āāāāāāāāāāāāāā¼āāāāāāāāā¼āāāāāāāā ā 1 ā store3 ā 80 ā āāāāāāāāāāāāāā©āāāāāāāāā©āāāāāāāā
Explanation:
- Product 0: Available in all stores, all rows included.
- Product 1: Available only in store1 and store3, store2 excluded due to NULL.
Still unsure what the problem is asking ?
Letās go through a few more examples, step by step, to make it clearer.