[英]How to PIVOT table with variable data in columns
All, 所有,
rownum respnum q2 q3
-----------------------------------
1 33 Missy 155-4
2 46 Melissa 55-98
3 73 Emma 998-4
How would you PIVOT the above table to show the desired results below? 您如何在上表中显示下面想要的结果? Keep in mind the original column headers are static (q2,q3,...) but the answers can vary.
请记住,原始列标题是静态的(q2,q3,...),但答案可能有所不同。
rownum respnum question answer
-----------------------------------
1 33 q2 Missy
1 33 q3 155-4
2 46 q2 Melissa
2 46 q3 55-98
3 73 q2 Emmat
3 73 q3 998-4
Thanks 谢谢
UnPivot would be more performant, but if you don't want to specify all the fields, consider the following: UnPivot的性能更高,但是如果您不想指定所有字段,请考虑以下几点:
Example 例
Select rownum
,respnum
,C.*
From YourTable A
Cross Apply ( values (cast((Select A.* for XML RAW) as xml))) B(XMLData)
Cross Apply (
Select question = a.value('local-name(.)','varchar(100)')
,answer = a.value('.','varchar(max)')
From B.XMLData.nodes('/row') as C1(n)
Cross Apply C1.n.nodes('./@*') as C2(a)
Where a.value('local-name(.)','varchar(100)') not in ('rownum','respnum')
) C
Returns 返回
rownum respnum question answer
1 33 q2 Missy
1 33 q3 155-4
2 46 q2 Melissa
2 46 q3 55-98
3 73 q2 Emma
3 73 q3 998-4
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.