Это известно как PIVOT
. Существует два способа выполнить эту операцию со статической или динамической версией.
Статическая версия - это когда вы жестко кодируете значения, чтобы стать столбцами:
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
Dynamic Pivot, получает список столбцов во время выполнения:
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)