[英]Pivot XML using XQuery and filter on attribute
Given the following XML (in an SQL column field called 'xfield'): 给定以下XML(在SQL列字段“ xfield”中):
<data>
<section>
<item id="A">
<number>987</number>
</item>
<item id="B">
<number>654</number>
</item>
<item id="C">
<number>321</number>
</item>
</section>
<section>
<item id="A">
<number>123</number>
</item>
<item id="B">
<number>456</number>
</item>
<item id="C">
<number>789</number>
</item>
</section>
</data>
How do you obtain the following table structure (with A, B & C as the column names): 如何获取以下表结构(以A,B和C作为列名):
A | B | C
987|654|321
123|456|789
Using SQL XQuery, I'm trying this (not surprisingly, it's invalid): 使用SQL XQuery,我正在尝试这样做(不足为奇,这是无效的):
SELECT
data.value('(./section/item[@ID = "A"]/number/[1])', 'int') as A,
data.value('(./section/item[@ID = "B"]/number/[1])', 'int') as B,
data.value('(./section/item[@ID = "C"]/number/[1])', 'int') as C
FROM Table CROSS APPLY [xfield].nodes('/data') t(data)
You're nearly there. 你快到了
You need to use nodes()
to shred the xml into the rows you want to work with - here, you want a resultset row for each section
element, so shred with 您需要使用
nodes()
将xml切成要处理的行 -在这里,您希望每个section
元素都有一个结果集行,因此要切碎
nodes('/data/section')
Once you've done that, you just need to make your xpath [1]
syntactically correct (and relative to the section
nodes you will be 'in'): 完成此操作后,只需要使xpath
[1]
语法上正确(相对于section
节点,您将“处于”状态):
data.value('(item[@id = "A"]/number)[1]', 'int') as A,
data.value('(item[@id = "B"]/number)[1]', 'int') as B,
data.value('(item[@id = "C"]/number)[1]', 'int') as C
And voila: 瞧:
A B C
----------- ----------- -----------
987 654 321
123 456 789
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.