I have following source and destination tables in sql server 2008R2. How can I do pivot(s) in TSQL to get to the destination from source.
SourceTbl
empId empIndex empState empStDate empEndDate
========================================================
10 1 AL 1/1/2012 12/1/2012
10 2 FL 2/1/2012 2/1/2013
15 1 FL 3/20/2012 1/1/2099
DestTbl
empId empState1 empState1StDate empState1EndDt empState2 empState2StDate empState2EndDt
=========================================================================================================
10 AL 1/1/2012 12/1/2012 FL 2/1/2012 2/1/2013
15 FL 3/20/2012 1/1/2099 NULL NULL NULL
Hoping that the empIndex will somehow help in the pivot.
Wow this was more complicated than i imagined, but I did get it to work great! thanks. This was my final version. The TextKey contains the data you want to turn into columns, and the TextValue is the value that ends up inside each cell.
Since you are using SQL Server there are several different ways that you can convert the rows into columns. You can use an aggregate function with a CASE expression:
See SQL Fiddle with Demo.
If you want to use the PIVOT function to get the result, then I would recommend first unpivoting the columns
empState
,empStDate
andempEndDate
so you will have multiple rows first. You can use the UNPIVOT function or CROSS APPLY to convert the data the code will be:See Demo. Once the data is unpivoted, then you can apply the PIVOT function so the final code will be:
See SQL Fiddle with Demo.
Th above versions will work great if you have a limited number of
empindex
, but if not then you can use dynamic SQL:See SQL Fiddle with Demo
You can use these queries to INSERT INTO your
DestTbl
, or instead of storing the data in this format, you now have a query to get the desired result.These queries place the data in the format: