---
tags: sql, LeetCode
disqus: HackMD
---
# 1795. Rearrange Products Table
本題主要考驗將資料 **橫轉直** 用法
這邊使用[UNPIVOT](http://jengting.blogspot.com/2010/11/sqlpivot-unpivot.html) 來解題
`Rearrange Products Table`
透過`leetcode 1795`[Rearrange Products Table](https://leetcode.com/problems/rearrange-products-table/)來練習
#### 使用table

product_id 是該表的主鍵。
此表中的每一行表示產品在 3 個不同商店的價格:store1、store2 和 store3。
如果該產品在商店中不可用,則該商店的列中的價格將為空。
## 題目說明:
編寫一個 SQL 查詢來重新排列 Products 表,以便每一行都有(product_id、store、price)。如果商店中沒有產品,請不要在結果表中包含具有該 product_id 和商店組合的行。
以任意順序返回結果表。
查詢結果格式如下例所示。

## 解題:
以下為第一個解法
```sql=
select product_id,store,price
from (
select product_id,store1,store2,store3 from Products
) as tmp
UNPIVOT
(price for store in(store1,store2,store3)) as temp
```
也可以使用union all
```sql=
SELECT
product_id,
'store1' AS store,
store1 AS price
FROM Products
WHERE store1 IS NOT NULL
UNION ALL
SELECT
product_id,
'store2' AS store,
store2 AS price
FROM Products
WHERE store2 IS NOT NULL
UNION ALL
SELECT
product_id,
'store3' AS store,
store3 AS price
FROM Products
WHERE store3 IS NOT NULL
```