You are given a Products table that contains product prices in different stores. Your task is to dynamically pivot this table so that each row represents one product and shows its price in each store as separate columns.
The table structure is:
product_id(int): The unique identifier for each productstore(varchar): The name of the storeprice(int): The price of the product in that store
You need to implement a procedure PivotProducts that reorganizes the data so that:
- Each row has one
product_id - Each store becomes a separate column
- The value is the price if the product is sold in that store, or
NULLif not - Store columns should be sorted in lexicographical order
Note: This is a hard problem requiring advanced SQL techniques. There will be at most 30 different stores.
Table Schema
| Column Name | Type | Description |
|---|---|---|
product_id
PK
|
int | The unique identifier for each product |
store
PK
|
varchar | The name of the store where the product is sold |
price
|
int | The price of the product in this store |
Input & Output
| product_id | store | price |
|---|---|---|
| 1 | Shop | 110 |
| 1 | LC_Store | 100 |
| 2 | Nozama | 200 |
| 2 | Souq | 190 |
| 3 | Shop | 1000 |
| 3 | Souq | 1900 |
| product_id | LC_Store | Nozama | Shop | Souq |
|---|---|---|---|---|
| 1 | 100 | 110 | ||
| 2 | 200 | 190 | ||
| 3 | 1000 | 1900 |
The input table has products sold in different stores. After pivoting, each product becomes a row with store names as columns. Store columns are sorted lexicographically: LC_Store, Nozama, Shop, Souq. Product 1 is sold in LC_Store and Shop only, so Nozama and Souq columns are null.
| product_id | store | price |
|---|---|---|
| 1 | A | 100 |
| 1 | B | 200 |
| 1 | C | 300 |
| product_id | A | B | C |
|---|---|---|---|
| 1 | 100 | 200 | 300 |
Single product sold in three stores A, B, C. All store columns have values since the product is available everywhere. Columns are ordered alphabetically.
| product_id | store | price |
|---|---|---|
| 1 | Store1 | 50 |
| 2 | Store2 | 75 |
| 3 | Store1 | 60 |
| 3 | Store2 | 80 |
| product_id | Store1 | Store2 |
|---|---|---|
| 1 | 50 | |
| 2 | 75 | |
| 3 | 60 | 80 |
Shows products with different store availability. Product 1 only in Store1, Product 2 only in Store2, Product 3 in both stores. NULL values indicate product not sold in that store.
Constraints
-
1 ≤ product_id ≤ 1000 -
1 ≤ price ≤ 100000 -
At most
30different stores -
storenames contain only letters and underscores -
Each
(product_id, store)combination is unique