Recently I’ve had a similar case when I needed to unpivot multiple related columns at the same time. It turned out that running multiple UNPIVOTs is actually slower and creates more complex execution plans than a single CROSS APPLY. The difference is getting more significant as row count grows.
Since I was unable to correctly format the post to display SQL queries inside, the details are available in another post.
Originally posted on Tuvian : Discussion forum for ASP.Net,C#,Ajax,JQuery,JavaScript,HTML,CSS..:
What is PIVOT and UNPIVOT operator in SQL Server
We can use the PIVOT and UNPIVOT relational operators to change a table-valued expression into another table. PIVOT rotates a table-valued expression by turning the unique values from one column in the expression into multiple columns in the output, and performs aggregations where they are required on any remaining column values that are wanted in the final output.
Please go through our previous post for PIVOT sample in SQL
Before UNPIVOT

Before UNPIVOT table
After UNPIVOT

UNPIVOT sample in SQL Server
A simple UNPIVOT sample in SQL Server
Here we are going to demonstrate a very simple UNPIVOT sample without any complexity. We are having a table named EmploymentHistory and its containing employee name with previous company name that particular employee worked.
Table Structure For showing simple UNPIVOT sample
CREATE TABLE EmploymentHistory (Id INT, Employee VARCHAR(500), Company1 VARCHAR(500), Company2 VARCHAR(500), Company3…
View original 300 more words
