Вы можете использовать динамический Sql для поворота с неизвестными именами столбцов.
пример:
-- Test table
CREATE TABLE YourTable
(
ID int primary key identity(1,1),
OtherId int not null,
Question varchar(30) not null,
Answer varchar(30) not null
);
-- Sample Data
insert into YourTable (OtherId, Question, Answer) values
(1, 'Q1', 'A1'), (1, 'Q2', 'A2'), (1, 'Q3', 'A3'),
(2, 'Q1', 'A4'), (2, 'Q2', 'A5'), (2, 'Q3', 'A6');
Запрос
DECLARE @Cols AS NVARCHAR(MAX);
DECLARE @DynSql AS NVARCHAR(MAX);
SELECT @Cols = CONCAT(@Cols + ', ', QUOTENAME(Question))
FROM YourTable
GROUP BY Question
ORDER BY Question;
SET @DynSql = N'SELECT *
FROM
(
SELECT OtherId, Question, Answer
FROM YourTable
) src
PIVOT
(
MAX(Answer)
FOR Question IN (' + @Cols + N')
) pvt
ORDER BY OtherId';
-- SELECT @DynSql AS DynSql;
EXECUTE sp_executesql @DynSql;
Результат:
OtherId Q1 Q2 Q3
1 A1 A2 A3
2 A4 A5 A6