SQLUSA

Microsoft SQL Server 2008 Best Practices

How to use the UNPIVOT operator?

 

Execute the following script in Query Editor to unpivot the StartDate and EndDate columns. Column types must be same for the UNPIVOT operator.

USE tempdb;

 

-- create a table for testing

select ID='I'+convert(varchar,BusinessEntityID)+'D'

             +convert(varchar,DepartmentID),

StartDate, EndDate

into EmployeeDept

from AdventureWorks2008.HumanResources.EmployeeDepartmentHistory

where EndDate is not null

go

 

--Unpivot the table.

SELECT *

FROM

   (SELECT ID, StartDate, EndDate

   FROM EmployeeDept) p

UNPIVOT

   (Date FOR DateType IN

      (StartDate, EndDate)

)AS unpvt;

GO

 

 

SQLUSA - The Best SQL Server 2008 Training in the World
 
 
SQLUSA.com Home Page