Microsoft SQL Server PIVOT / UNPIVOT

Help us to keep this website almost Ad Free! It takes only 10 seconds of your time:
> Step 1: Go view our video on YouTube: EF Core Bulk Extensions
> Step 2: And Like the video. BONUS: You can also share it!

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.



Got any Microsoft SQL Server Question?