WHAT IS PIVOT AND UNPIVOT IN SQL SERVER?

PIVOT and UNPIVOT are relational operators. PIVOT rotates a table-valued expression by turning the unique values from one column in the expression into multiple columns in the output. And PIVOT runs aggregations where theyโ€™re required on any remaining column values that are wanted in the final output. UNPIVOT carries out the opposite operation to PIVOT by rotating columns of a table-valued expression into column values.

Syntax-

SELECT <non-pivoted column>, [first 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], โ€ฆ [last pivoted column]) ) AS <alias for the pivot table> 

<optional ORDER BY clause>;

Example-

Table-ย SalesTable

ProductYearSale
Pen20201000
Pen20212000
Pencil20205000
Pencil20211000
Pen20202000

Result Set-ย PivotTable

YearPenPencil
202030005000
202120001000
SELECT Year, Pen, Pencil

FROM (SELECT Product, Year, Sale FROM SalesTable) AS Table1   

PIVOT (SUM(Sale)

FOR Product

IN (Pen, Pencil)) AS PivotTable   

ORDER BY PivotTable.Year

Dynamic PIVOT table query-

CREATE PROCEDURE DynamicPivot 

  @PivotColumn NVARCHAR(255), 

  @PivotList NVARCHAR(255) 

AS 

BEGIN 

 DECLARE @Query NVARCHAR(MAX);   

 SET @PivotQuery = Nโ€™ 

    SELECT * FROM (SELECT [Product], [Year], [Sale] FROM SalesTable) AS Table1 

    PIVOT (SUM([Sale]) FOR [โ€˜+@PivotColumn+โ€™] IN (โ€˜+@PivotList+โ€™)) AS PivotTableโ€™; 

  EXEC(@PivotQuery) 

END


Executing the stored procedure-

EXEC DynamicPivot  Nโ€™Productโ€™, N'[Pen], [Pencil]โ€™

UNPIVOT Operator-

UNPIVOT carries out almost the reverse operation of PIVOT, by rotating columns into rows.

SELECT (column_names)  

FROM (table_name)  

UNPIVOT 

 (  

   Aggregate_function (column to be aggregated) 

   FOR PivotColumn IN (pivot column values) 

 ) AS (alias_name)

Example-

Declares a temporary table variable @Tab:

DECLARE @Tab TABLE   

(   

   Year int,   

   Pen varchar(45), 

   Pencil varchar(45) 

) 

Insert values into this table as below:

INSERT INTO @Tab   

SELECT Year, Pen, Pencil FROM    

(SELECT Product, Year, Sale FROM SalesTable ) AS Table1   

PIVOT   

(SUM(Sale) FOR Product IN (Pen, Pencil)) AS PivotTable   

ORDER BY PivotTable.Year ;

Perform UNPIVOT operation:

SELECT Product, Year, Sale FROM @Tab t   

UNPIVOT   

(   

Sale FOR Product IN (Pen, Pencil)   

) AS UnpivotTable; 

Posted

in

Tags:

Comments

Leave a Reply