Looking for sql-server Answers? Try Ask4KnowledgeBase
Looking for sql-server Keywords? Try Ask4Keywords

Microsoft SQL ServerPIVOT / UNPIVOT


  • SELECT <non-pivoted column>,
    [first pivoted column] AS <column name>,
    [second pivoted column] AS <column name>,
    [last pivoted column] AS <column name>
    (<SELECT query that produces the data>)
    AS <alias for the source query>
    <aggregation function>(<column being aggregated>)
    [<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>;


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.