MSSQL 使用 PIVOT 翻轉資料表並重新命名欄位

SELECT Id, p.[1] as 狀況一, p.[2] as 狀況二, p.[3] as 狀況三
FROM [dbo].[Table_1]
PIVOT (
	MAX(數量)
	FOR 狀況 IN ([1],[2],[3])
) p

如果 FROM 是一個子查詢要給別名才不會報錯

SELECT Id, p.[1] as 狀況一, p.[2] as 狀況二, p.[3] as 狀況三
FROM (
	SELECT *
	FROM [dbo].[Table_1]
) t
PIVOT (
	MAX(數量)
	FOR 狀況 IN ([1],[2],[3])
) p

發佈留言