開始使用免費開始

將列轉換成欄

在本課中,你學到 PIVOT 會把某欄位中的唯一值轉成多個欄位。

分析 paper_shop_monthly_sales 的資料後,你發現該資料表的結構不適合你想產出的報表。

你想產生如下所示的報表:

|year_of_sale|notebooks|pencils|crayons|
|------------|---------|-------|-------|
| 2018       | 150     | 150   | 80    |
| 2019       | 230     | 130   | 170   |

也就是說,你想把現在位於列的資料轉成欄,並且針對每一年加總單位數量。

如同你在前面練習所學,產品名稱與單位數量需要先拆開。這已在子查詢中完成,請看一下。

本練習屬於課程

在 SQL Server 資料庫中清理資料

檢視課程

練習說明

  • 為每個產品選取透過樞紐化後的欄位。
  • PIVOT 運算子中納入單位數量的加總。
  • FOR 陳述式之後,加入將成為欄名的值所屬欄位名稱。
  • PIVOT 運算子命名為 paper_shop_pivot

動手互動練習

試著完成這個範例程式碼,體驗一下這個練習。

SELECT
	year_of_sale,
    -- Select the pivoted columns
	___, 
	___, 
	___
FROM
   (SELECT 
		SUBSTRING(product_name_units, 1, charindex('-', product_name_units)-1) product_name, 
		CAST(SUBSTRING(product_name_units, charindex('-', product_name_units)+1, len(product_name_units)) AS INT) units,	
		year_of_sale
	FROM paper_shop_monthly_sales) sales
-- Sum the units for column that contains the values that will be column headers
PIVOT (SUM(___) FOR ___ IN (notebooks, pencils, crayons))
-- Give the alias name
AS ___
編輯並執行程式碼