PIVOT語法剖析:
PIVOT的語法分三層,用三個步驟來使用。
第一步驟:先把要PIVOT的原始資料查詢(Query)好。
第二步驟:設定好PIVOT的欄位與方式。
第三步驟:依PIVOT好了的資料,呈現結果。
SELECT <non-pivoted column>, ---- 第三步驟在此,呈現PIVOT後的資料。
[first pivoted column] AS <column name>,
[second pivoted column] AS <column name>,
...
[last pivoted column] AS <column name>
FROM
(<SELECT query that produces the data>) ---- 第一步驟在此,準備資料(Query)。
AS <alias for the source query>
PIVOT ---- 第二步驟在此,依第一步驟的資料欄位來設定PIVOT方式。
(
<aggregation function>(<column being aggregated>)
FOR
[<column that contains the values that will become column headers>]
IN ( [first pivoted column], [second pivoted column],
... [last pivoted column])
) AS <alias for the pivot table>
<optional ORDER BY clause>;