將欄轉成列
在上一個練習中,你把列中的產品名稱轉成欄,接著彙總每一年的產品銷售數量。
假設你已將上一題的結果存到一個名為 pivot_sales 的新資料表,現在你想把 notebooks、pencils、crayons 這三個欄位轉成列值。
預期結果如下:
| year_of_sale | units | product_name |
|--------------|-------|--------------|
| 2018 | 150 | notebooks |
| 2018 | 150 | pencils |
| 2018 | 80 | crayons |
| 2019 | 230 | notebooks |
| 2019 | 130 | pencils |
| 2019 | 170 | crayons |
本練習屬於課程
在 SQL Server 資料庫中清理資料
練習說明
- 使用合適的運算子把欄轉換成列。
- 寫出用來承接被轉出欄位名稱的輸出欄位名稱。
- 寫出你想轉成列的欄位名稱。
- 將
UNPIVOT運算子取別名為unpivot_sales。
動手互動練習
試著完成這個範例程式碼,體驗一下這個練習。
SELECT * FROM pivot_sales
-- Use the operator to convert columns into rows
___
-- The resulting column that will contain the turned columns into rows
(units FOR ___ IN (___, ___, ___))
-- Give the alias name
AS ___