Unpivot in SQL

Un-pivot is to convert column data in to row data. I will recommend to check my blog Here on pivot in SQL before learning Un-pivot.

I will use the same Sales table for this demo. We used below query to pivot region values in to column.

Select SalesPerson,INDIA,Europe,US
From
(Select SalesPerson,Region,Sale from Sales) as Sales
PIVOT
(SUM(Sale)
FOR Region
IN (INDIA,Europe,US)
)
AS PIVOTTABLE

Now we want to Un-pivot Region values. Here is the query to do the job

SELECT PersonName,Region,Sale
From
(Select SalesPerson,INDIA,Europe,US
From
(Select SalesPerson,Region,Sale from Sales) as Sales
PIVOT
(SUM(Sale)
FOR Region
IN (INDIA,Europe,US)
)
AS PIVOTTABLE
) AS PSET
UNPIVOT
(Sale
FOR rEGION
IN (INDIA,Europe,US) )
AS UPSET;

Author: Sauras Pandey

Sauras Pandey is an MCP, SQL Server DBA/Architect with 7+ years of experience working in a variety of environments

Leave a Reply

Your email address will not be published.