I am using sql server 2008 and I want to cross tab this table
Month Affec KPI Total KPI_% Out rep_in_10 ftm
Jan-11 30565 34623 42003 82.4 7380 7003 5024
Jan-12 20955 25915 27857 93 1942 4754 3518
Feb-11 27754 27757 36483 76.1 8726 5648 4189
Feb-12 19513 25188 26962 93.4 1774 5768 4185
Mar-11 22838 23758 29951 79.3 6193 4394 3282
Mar-12 18778 25098 26177 95.9 1079 5784 4105
Apr-11 20235 21950 25917 84.7 3967 3895 2967
to
Jan-11 Jan-12 Feb-11 Feb-12 Mar-11 Apr-11
Affec 30565
KPI 34623
Total 42003
KPI_% 82.4
Out 7380
rep_in_10 7003
For this type of data transformation, you will need to use the
UNPIVOTfunction and then apply thePIVOTfunction in SQL Server.There are two ways to perform this, either hard-coding the values with a static version of using dynamic sql to generate the values as run-time.
Static Version:
The
UNPIVOTpiece of this takes the data from your multiple columns and transforms it into two rows. Note, the one thing to keep in mind with unpivot is that the datatypes must be the same. So you might have to perform a data type conversion on the data.:See SQL Fiddle with Demo
Result:
Then you apply the
PIVOTto the months:See SQL Fiddle with Demo
Result:
Dynamic Version:
The above works great, if you have a known number of values but it your values are unknown then you will want to use dynamic sql. I am going to guess that you will want a dynamic version since you will have a unknown number of dates:
See SQL Fiddle with Demo
The result will be the same as the dynamic version.
UNION ALL/CASE with aggregate:
Lastly, if you do not have access to either the
UNPIVOTorPIVOTfunctions, then you can use aUNION ALLto unpivot and an aggregate function with aCASEto pivot the data:See SQL Fiddle with Demo