I have the following two tables:
Quiz Table:
QuizNo | Status
1 Reviewed
2 Not Reviewed
Quiz Response Table:
QuizNo | QuestionID | Response
1 11 Yes
2 13 No
2 11 Yes
1 13 No
This is the expected result (11 and 13 being question ID's):
QuizNo | Status | 11 | 13
1 Reviewed Yes No
2 Not Reviewed Yes No
This is my current query, which is not functioning:
DECLARE @cols AS NVARCHAR(MAX),
@query AS NVARCHAR(MAX)
select @cols = STUFF((SELECT ',' + QUOTENAME(QuestionID)
from Quiz
INNER JOIN QuizResponse x ON QuizNo = x.QuizNo
group by QuestionID, QuizNo
order by QuestionID
FOR XML PATH(''), TYPE
).value('.', 'NVARCHAR(MAX)') ,1,1,'')
set @query = N'SELECT ' + @cols + N' from
(
select QuestionID
from QuizResponse
) x
pivot
(
max(QuestionID)
for QuestionID in (' + @cols + N')
) p '
exec sp_executesql @query;
How would you complete/change the query to get the expected result?
TIA!