I am trying to write a sql statement that creates a pivot table.
The data is a list of survey responses and is made from a join query involving tables respondent, response and answer. The answer table is structured as below:
______________________________________________________________
|AnswerID|ResponseID|QuestionID|AnswerComment |
| 1 | 1 | 1 |This is answer 1 |
| 2 | 1 | 2 |This is answer 2 |
| 3 | 1 | 3 |This is answer 3 |
| 4 | 2 | 1 |Answer 1 Respondent 2 |
| 5 | 2 | 3 |Resp 2, No Q.2 |
| 6 | 3 | 2 |I answered Q.2 only |
|____________________________________________________________|
Respondent looks like:
______________________________________________________________
|RespondentID|GivenName|Surname|age, gender, blah blah |
|____________________________________________________________|
Response:
______________________________________________________________
|ResponseID|ResponseDate|RespondentID|Attachment |
|____________________________________________________________|
and Question:
_____________________________________________________
|QuestionID|QuestionNumber|QuestionText| |
|___________________________________________________|
I want my output in the form of:
________________________________________________________________________________________
|RespondentInfo|ResponseDate|1 |2 |3 |
|Respondent 1 |15/10/2012 |This is answer 1 |This is answer 2 |This is answer 3|
|Respondent 2 |17/10/2012 |Answer 1 Respondent 2 | |Resp 2, No Q.2 |
|Respondent 3 |19/10/2012 | |I answered Q.2 only| |
|______________________________________________________________________________________|
I want to get one line per respondent with each answer in the corresponding column. The query I have created – although it pivots the answers to the correct columns – provides a new row for each answer with nulls in all the blank columns.
My sql:
SELECT Respondent, ResponseDate,
[1], [2], [3]
FROM (
SELECT Respondent.Surname + ', ' + FirstName as RespondentInfo,
Response.ResponseDate,
isnull(Answer.AnswerComment, '') as Answer,
Qustion.QuestionNumber
FROM Answer INNER JOIN
Question ON Answer.QuestionID = Question.QuestionID INNER JOIN
Response ON Answer.ResponseID = Response.ResponseID INNER JOIN
Respondent ON Response.RespondentID = Respondent.RespondentID
) as ResponseQuery
PIVOT (
max(Answer)
FOR ResponseQuery.QuestionNumber in ([1], [2], [3])
) AS OutputTable
I think the issue is because I am not using an aggregate function so have defaulted to max(). Can anyone point me in the right direction.
Apologies if my question is too verbose.
The problem is the source, not the pivot.
It’s hard to tell without seeing the other tables, but using your example table
produces the output in the form you’re after.
If you can’t figure out how to adjust the source to provide the data you want, you can join after the pivot by adding something like…
after the above pivot to give
etc…