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
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
Pivoted table
Unpivot Example



No comments:
Post a Comment