Wednesday, October 14, 2015

SQL - Pivot & Unpivot

Pivot & Unpivot are relational operators.
Pivot is used to rotate table valued expression. In a table valued expression, it turns unique values of one column into multiple columns and perform aggregation on any of other columns that is required in output.
Unpivot is used to perform opposite operation of Pivot, In a table valued expression, it turns multiple columns into one column values with multiple rows.

Syntax
SELECT <non-pivoted column>,
    [first pivoted column] AS <column name>,
    [second pivoted column] AS <column name>,
    ...
    [nth pivoted column] AS <column name>
FROM
    (<SELECT query that produces the data>)
    AS <alias for the main 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],
    ... [nth pivoted column])
) AS <alias for the pivot table>

<optional ORDER BY clause>

Example
 Table valued sql expression
Pivoted table 

Unpivot Example



No comments:

Post a Comment

CI/CD - Safe DB Changes/Migrations

Safe DB Migrations means updating your database schema without breaking the running application and without downtime . In real systems (A...