Current query:
SELECT order_id AS OrderNumber, ordName, ordLastName, question, answer
FROM cart_survey
JOIN orders
ON cart_surv
This is known as a PIVOT there are two ways to perform this operation with a Static version or dynamic version.
Static Version is when you hard-code the values to become columns:
SELECT *
FROM
(
SELECT order_id AS OrderNumber, ordName, ordLastName, question, answer
FROM cart_survey
JOIN orders
ON cart_survey.order_id=orders.ordID
JOIN survey_answers
ON survey_answers.id=cart_survey.answer_id
JOIN survey_questions
ON survey_questions.id=cart_survey.question_id
) x
pivot
(
min(answer)
for question in ([Type of Surgery:], [Month of Surgery:],
[Year of surgery:], [Current Ostomy System Brand:],
[Degree of Satisfaction:])
) p
A Dynamic Pivot, gets the list of the columns at run-time:
DECLARE @cols AS NVARCHAR(MAX),
@query AS NVARCHAR(MAX)
select @cols = STUFF((SELECT distinct ', ' + QUOTENAME(question)
from survey_questions
FOR XML PATH(''), TYPE
).value('.', 'NVARCHAR(MAX)')
,1,1,'')
set @query
= 'SELECT OrderNumber, ordname, orderLastName,' + @cols + ' from
(
SELECT order_id AS OrderNumber, ordName, ordLastName, question, answer
FROM cart_survey
JOIN orders
ON cart_survey.order_id=orders.ordID
JOIN survey_answers
ON survey_answers.id=cart_survey.answer_id
JOIN survey_questions
ON survey_questions.id=cart_survey.question_id
) x
pivot
(
min(answer)
for question in (' + @cols + ')
) p '
execute(@query)