I have a table Survey_Data_Response that is populated with an ‘insert into’ statement from two tables – Survey_Question and Survey_Response, they are joined on the QuestionID.
I want to use a SP to pivot the Survey_Data_Response table and save the results to a temp table so I can query it to develop reports.
The Survey_Data_Response table has fields – QuestionID, ResponseID, Question, Response, ResponseDateTime,moduleID.
The number of questions can change depending on the survey.
QuestionID Question Response ResponseDateTime ResponseID ModuleID
123 Age 34 2011-06-06 18:21:00 ABC 123
345 Gender M 2011-06-06 18:21:00 DEF 123
567 Phone 444-4444 2011-06-06 18:21:00 HIG 123
123 Age 23 2011-06-07 12:01:00 MNO 123
789 Postal Code 90988 2011-06-07 12:01:00 XYZ 123
I need to pivot the table to look like this, the questions as columns and the response in the appropriate field.
ResponseID Age Gender Phone Postal Code ResponsDateTime
ABC 34 M 444-4444 2011-06-06 18:21:00
XYZ 23 90988 2011-06-07 12:01:00
I’ve tried numerous pivot queries over the last 2 days but haven’t had any luck. This is where I’m at, it returns the column headers, but the responses to the questions aren’t being populated.
DECLARE @cols VARCHAR(1000)
DECLARE @sqlquery VARCHAR(2000)
SELECT @cols = STUFF(( SELECT distinct ',' + QuoteName(question)
FROM temp_SURVEY_DATA FOR XML PATH('') ), 1, 1, '')
SET @sqlquery = 'SELECT * FROM
(SELECT DynamicQuestionResponseID,question,moduleid
FROM temp_SURVEY_DATA ) base
PIVOT (max(moduleid) FOR question
IN (' + @cols + ')) AS finalpivot'
EXECUTE ( @sqlquery )
Can someone help me understand why this Pivot doesn’t work and how to make it work?
Thanks
this should give you what you want:
Results: