Saturday, December 25, 2010

SQL Server 2005 - Transform Multiple Rows into Multiple Columns

Having this kind of table in SQL Server:


We would like to get to the following structure using SQL code:

Click the picture to see the full size.

This is a bit different from a PIVOT which can be done using the SQL Server function of the same name. What we wanted to get is for each combintation of ForeignKey1 and ForeignKey2, we would like to have all the possible combinations of Attribute1 and Attribute2 in the same row.
This could be done using a Transact SQL stored procedure of course but the following SQL code is the easiest approach if we know the maximum number of possibility for each combination of Foreign Keys:

 

 Click the picture to see the full size.