Stats

181 Contributors: 4
2017-05-10
Licensed under: CC-BY-SA

Not affiliated with Stack Overflow
Rip Tutorial: info@zzzprojects.com

Download eBook

PIVOT / UNPIVOT

Download sql-server eBook

Syntax

  • 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>;

Remarks

Using PIVOT and UNPIVOT operators you transform a table by shifting the rows (column values) of a table to columns and vise-versa. As part of this transformation aggregation functions can be applied on the table values.

Related Examples