Lets say I have the following table representing results from a user survey system.
SurveyID ResponseID QuestionID Answer
-------- ---------- ---------- ------
1 1 1 'Answer 1'
1 1 2 'Answer 2'
1 1 3 'Answer 3'
1 2 1 'red'
1 2 2 'blue'
1 2 3 'green'
What I want is a pivoted output such that shown below.
SurveyID ResponseID Q1 Q2 Q3
-------- ---------- -- -- --
1 1 'Answer 1' 'Answer 2' 'Answer 3'
1 2 'red' 'blue' 'green'
I know how to achieve this if there were always only the same three questions but this database hosts multiple surveys which could have any number of unique QuestionIDs so I need the Q1, Q2, Q3 columns to be dynamic depending upon the number and IDs of that survey's questions.
I thought this would be a fairly standard problem but I cannot find anything that fully satisfies this issue. Any solution must work with SQL Server 2005.
Hope that makes sense. Thanks.