[英]Dynamic sql pivot values coming in seperate columns
HI I am trying to write dynamic pivot as I have over 100 columns嗨,我正在尝试编写动态数据透视表,因为我有 100 多列
ID Question Answer
1 Name peter
1 DOB 11/12/2003
1 address …..
1 Issue1 d
1 Issue2 a
2 Name sam
2 DOB 10/01/1998
2 address …..
2 Issue1 p
2 Issue2 f
I want the output like this:我想要这样的输出:
ID Name DOB address Issue1 Issue2
1 peter 11/12/2003 …. d a
2 sam 10/01/1998 …. p f
Here is the code that I have used:-这是我使用的代码:-
select @cols = STUFF((SELECT distinct ',' + QUOTENAME(Question)
from #temp
FOR XML PATH(''), TYPE
).value('.', 'NVARCHAR(MAX)')
,1,1,'')
set @query = N'SELECT ID + @cols + N'
from #temp
pivot
(
max([answer])
for Question in (' + @cols + N')
) p '
exec sp_executesql @query;
But I am getting each answer in a separate row.但是我在单独的一行中得到每个答案。 I want all the answers of an ID to come in one row.我希望一个 ID 的所有答案都排成一行。 Can somebody help me.有人可以帮助我。 Appreciate your time on this.珍惜你在这方面的时间。 Thank you.谢谢你。
I am getting the output like this, which is not I want.我得到这样的输出,这不是我想要的。 I want the output as above.我想要上面的输出。
ID Name DOB address Issue1 Issue2
1 Peter
1 11/12/2003
1 …
1 d
1 a
It looks like you are looking for a way to dynamically create a pivot based on your table without aggregation.看起来您正在寻找一种无需聚合即可根据您的表动态创建数据透视表的方法。 You can try the following:您可以尝试以下操作:
SELECT @cols = STUFF((SELECT ',' + QUOTENAME(Question)
FROM #TEMP
GROUP BY QUESTION
ORDER BY QUESTION
FOR XML PATH(''), TYPE
).value('.', 'NVARCHAR(MAX)')
,1,1,'')
set @query = 'SELECT ID,' + @cols + ' FROM
(
SELECT ID, Question, Answer
FROM #TEMP
) x
pivot
(
MAX(Answer)
for Question in (' + @cols + ')
) p '
execute(@query);
Expected Output:预期输出:
+----+---------+------------+--------+--------+-------+
| ID | address | DOB | Issue1 | Issue2 | Name |
+----+---------+------------+--------+--------+-------+
| 1 | ….. | 11/12/2003 | d | a | peter |
| 2 | ….. | 10/1/1998 | p | f | sam |
+----+---------+------------+--------+--------+-------+
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.