1 頁 (共 1 頁)

[SQL Server]使用Pivot的語法

發表於 : 2010年 7月 7日, 10:39
tim
在 SQL Server 2005 起, 支援了 pivot 及 unpivot 的語法, 用來做一些轉置及特殊分析報表使用, 很方便, 在之前沒有這種功能時, 可以透過條件方式(case when)語法, 但會有不定輸出欄位數的困難, 子查詢或暫存表也是解決的方式. 不過使用 pivot 語法將能更有效解決這個問題, 微軟參考資料如下:

http://technet.microsoft.com/zh-tw/libr ... 90%29.aspx

代碼: 選擇全部

SELECT <非樞紐資料行> ,

    [第一個樞紐資料行] AS <資料行名稱> ,

    [第二個樞紐資料行] AS <資料行名稱> ,

    ...

    [最後一個樞紐資料行] AS <資料行名稱>

FROM

    ( <產生資料的 SELECT 查詢> )

    AS <來源查詢的別名>

PIVOT

(

    <aggregation function>( <要彙總的資料行> )

FOR

[<含有將成為資料行標頭值的資料行>]

    IN ( [第一個樞紐資料行] , [第二個樞紐資料行] ,

    ... [最後一個樞紐資料行] )

) AS <樞紐資料表的別名>

<選擇性 ORDER BY 子句>

SELECT <non-pivoted column>,

    [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>)

    AS <alias for the source query>

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>
from 子句的 pivot : http://technet.microsoft.com/zh-tw/libr ... 90%29.aspx