我需要使用自定义列名来旋转表格。请参阅下表格式。
当前格式:
ID question Answer
4482515 I would like to be informed by mail. No
4482515 Plan to Purchase? Over 12 months
4482515 Test Question Text some Answer
我想以以下格式显示数据。
所需格式:
ID question 1 Answer1 question 2 Answer 2
4482515 I would like to be informed by mail. NO Plan to Purchase? Over 12 months
请注意:我不知道一行中的问题和答案的数量,因此该列的 question1 Answer1 应该是动态生成的。
谢谢
编辑:感谢您的帮助,我尝试一下您提供给我的动态代码并收到此错误。
Msg 8167, Level 16, State 1, Line 1
The type of column "answer" conflicts with the type of other columns specified in the UNPIVOT list.
我的表是
RID Question Answer
4482515 Some Question1 Some Answer1
4482515 Some Question2 Some Answer2
4482515 Some Question3 Some Answer3
4484094 Some Question1 Answer1
4484094 Some Question2 Answer2
4484094 Some Question3 Answer3
4484094 Some Question4 Answer4
我打印出 SQL,结果如下。
SELECT rid, [question1],[answer1],[question2],[answer2],[question3],[answer3],[question4],[answer4],[question5],[answer5],[question6],[answer6]
from
(
select rid,
col+cast(rn as varchar(10)) col,
value
from
(
select rid, question, answer,
row_number() over(partition by rid order by rid, question) rn
from #tmp_question
) src
unpivot
(
value
for col in (question, answer)
) unpiv
) d
pivot
(
max(value)
for col in ([question1],[answer1],[question2],[answer2],[question3],[answer3],[question4],[answer4],[question5],[answer5],[question6],[answer6])
) p
我的原始 SQL 代码也在下面
DECLARE @cols AS NVARCHAR(MAX),
@query AS NVARCHAR(MAX)
select @cols = STUFF((SELECT ',' + QUOTENAME(c.col+cast(rn as varchar(10)))
from
(
select row_number() over(partition by rid
order by rid, question) rn
from #tmp_question
) d
cross apply
(
select 'question' col, 1 sort union all select 'answer', 2
) c
group by col, rn, sort
order by rn, sort
FOR XML PATH(''), TYPE
).value('.', 'NVARCHAR(MAX)')
,1,1,'')
set @query = 'SELECT rid, ' + @cols + '
from
(
select rid,
col+cast(rn as varchar(10)) col,
value
from
(
select rid, question, answer,
row_number() over(partition by rid order by rid, question) rn
from #tmp_question
) src
unpivot
(
value
for col in (question, answer)
) unpiv
) d
pivot
(
max(value)
for col in (' + @cols + ')
) p '
--print @query
execute(@query);
等待您的热心帮助!