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.

Hints

0
Ā 
Test Case

Input:

Products