Static Pivot:
create table temp
(
id int,
name varchar(10),
question varchar(10),
answer varchar(10)
)
INSERT into temp VALUES (0,'test', 'vault','a');
INSERT into temp VALUES (0,'test', 'Container','1');
INSERT into temp VALUES (1,'foo', 'vault','b');
INSERT into temp VALUES (1,'foo', 'Container','2');
select *
from
(
select id, name, question, answer
from temp
) x
pivot
(
max(answer)
for question in ([container], [vault])
) p
drop table temp
DECLARE @cols AS NVARCHAR(MAX),
@query AS NVARCHAR(MAX);
select @cols = STUFF((SELECT distinct ',' + QUOTENAME(c.question)
FROM temp c
FOR XML PATH(''), TYPE
).value('.', 'NVARCHAR(MAX)')
,1,1,'')
set @query = 'SELECT id, name, ' + @cols + ' from
(
select id, name, question, answer
from temp
) x
pivot
(
max(answer)
for question in (' + @cols + ')
) p '
execute(@query)
:
