请找到需要转置的表格(OututTable)。这里的QuestionID是通过连接两个值形成的 - [问题:AnswerID]
refID | SessionID | QuestionID | AnswerValue
9000 | 205545715 | [4907] | Good morning
12251 | 205543469 | [10576:16307] | 3
12255 | 205543469 | [10907:17001] | 4
13157 | 205543703 | [10576:16307] | 3
14387 | 205543493 | [10907:17001] | 2
14389 | 205543493 | [10911:17007] | 3
预期输出每个SessionID应该有一行,而列数是动态的
SessionID | [4097] | [10576:16307] | [10907:17001] | [10911:17007]
205545715 |Good morning | | |
205543469 | | 3 | 4 |
205543703 | | 3 | |
205543493 | | | 2 | 3
我有上述格式的输出,但只插入了NULL值而不是Answer值
我在想列名可能不匹配。任何帮助都会很棒!请告诉我。
代码:
set @Questions = (STUFF((SELECT distinct ',[' + cast(i.SessionID as varchar(20)) + ']'
FROM OutputTable i
FOR XML PATH(''), TYPE).value('.','VARCHAR(max)'), 1, 1, ''))
print @Questions
set @SQLQuery = 'select QuestionID,'+ @Questions +' from '+'('+ 'select SessionID,QuestionID,AnswerValue from OutputTable '+ ') p '+ 'PIVOT'+ '('+'max(Answervalue)'+'FOR p.SessionID IN ('+ @Questions +')' +') as pvt'
答案 0 :(得分:0)
好问题!问题在于QuestionID中的括号。虽然这些对于Pivot Column Aliases是必需的,但它们不能用作字符串过滤器。
代码示例还会为期望的输出切换QuestionID和SessionID。
此代码将返回预期输出,排序略有不同。此处创建临时表以模拟OutputTable对象。这需要使用数据库表进行切换。
declare
@Questions varchar(max),
@SQLQuery varchar(max)
create table #OutputTable
(
refID int,
SessionID int,
QuestionID varchar(50),
AnswerValue varchar(50)
)
insert into #OutputTable
values
(9000,205545715,'[4907]','Good morning'),
(12251,205543469,'[10576:16307]','3'),
(12255,205543469,'[10907:17001]','4'),
(13157,205543703,'[10576:16307]','3'),
(14387,205543493,'[10907:17001]','2'),
(14389,205543493,'[10911:17007]','3')
set @Questions = (STUFF((SELECT distinct ',' + cast(i.QuestionID as varchar(20))
FROM #OutputTable i
FOR XML PATH(''), TYPE).value('.','VARCHAR(max)'), 1, 1, ''))
set @SQLQuery = '
select SessionID,'+ @Questions +'
from (
select
SessionID,
replace(replace(QuestionID,''['',''''),'']'','''') QuestionID,
AnswerValue
from #OutputTable
) p
PIVOT (
max(Answervalue)
FOR p.QuestionID IN ('+ @Questions +')
) as pvt
order by SessionID desc'
exec(@SQLQuery)