Given a Products table with dynamic store columns, implement a procedure UnpivotProducts to reorganize the data.
The table has a product_id column and multiple store columns (store_name1, store_name2, etc.) containing prices. Each store column contains the price of the product in that store, or NULL if not available.
Requirements:
- Transform the wide table format into a narrow format
- Each row should contain:
product_id,store, andprice - Exclude rows where the product is not available in a store (price is NULL)
- Handle dynamic column names that may change between test cases
- Store names can be any valid column name
Table Schema
| Column Name | Type | Description |
|---|---|---|
product_id
PK
|
int | Primary key identifying the product |
store1
|
int | Price in store1, NULL if not available |
store2
|
int | Price in store2, NULL if not available |
store3
|
int | Price in store3, NULL if not available |
Input & Output
| product_id | store1 | store2 | store3 |
|---|---|---|---|
| 1 | 10 | 15 | |
| 2 | 20 | 25 |
| product_id | store | price |
|---|---|---|
| 1 | store1 | 10 |
| 1 | store2 | 15 |
| 2 | store2 | 20 |
| 2 | store3 | 25 |
The wide table with store columns is unpivoted into a narrow format. Product 1 is available in store1 (price 10) and store2 (price 15) but not in store3, so no row for that combination. Product 2 is available in store2 and store3 but not store1.
| product_id | store1 | store2 |
|---|---|---|
| 3 |
| product_id | store | price |
|---|
When a product has NULL prices in all stores, no rows are included in the output since the product is not available anywhere.
| product_id | amazon |
|---|---|
| 1 | 100 |
| 2 | 200 |
| product_id | store | price |
|---|---|---|
| 1 | amazon | 100 |
| 2 | amazon | 200 |
Even with just one store column, the dynamic approach works correctly, transforming the data into the required format with store name as a value.
Constraints
-
1 ≤ product_id ≤ 1000 -
1 ≤ number of stores ≤ 30 -
0 ≤ price ≤ 1000orNULL - Store column names are dynamic and can vary between test cases