I have a SQL Server view with following data:
ID clientID surveyID questionID q_optionID q_ans_text
-----------------------------------------------------------------
1 1 1 1 NULL Yes
2 1 1 2 18 NULL
3 1 1 3 19 NULL
4 2 1 1 NULL No
5 2 1 2 18 NULL
6 2 1 3 19 NULL
7 3 2 1 NULL Yes
8 3 2 2 15 NULL
9 3 2 3 13 NULL
I want the result to be something like this:
ClientID SurveyID Q1 Q2 Q3
------------------------------------
1 1 Yes 18 19
2 1 No 18 19
3 2 Yes 15 13
Where the conditional NULL values are ignored and the proper answer is placed in the column. I have looked at Pivot table examples, but they seem to be focusing on single column pivots.
In order to perform this transformation you will need to
UNPIVOTand thenPIVOTthe data. TheUNPIVOTwill take the values from yourq_optionIDandq_ans_textcolumns and transform it into two columns one with the value and the column name.There are two ways that you can
PIVOTthis, you can hard-code all of the values using a static version or you can use dynamic sql. In order toUNPIVOTthe data you need to be sure that the data is of the same datatype, so converting might be necessary.Static PIVOT:
See SQL Fiddle with Demo
Unpivot result:
Then you will apply the
PIVOTto the result to get your final product.See SQL Fiddle with demo
Dynamic PIVOT:
See SQL Fiddle with Demo
UNION ALL/Aggregate with Case Version:
Now, if you are working in a system that does not have
PIVOTthen you can use aUNION ALLtoUNPIVOTand an aggregate function with aCASEtoPIVOT:See SQL Fiddle with Demo
All three will produce the same result: