【问题标题】:Pivot XML using XQuery and filter on attribute使用 XQuery 透视 XML 并过滤属性
【发布时间】:2010-07-30 13:07:19
【问题描述】:

给定以下 XML(在名为“xfield”的 SQL 列字段中):

<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>

如何获得如下表结构(以A、B、C为列名):

 A | B | C
987|654|321
123|456|789

使用 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)

【问题讨论】:

    标签: sql-server xml xquery-sql


    【解决方案1】:

    你快到了。

    您需要使用 nodes() 将 xml 分解为您要使用的 - 在这里,您需要为每个 section 元素创建一个结果集行,因此使用分解

    nodes('/data/section')
    

    一旦你这样做了,你只需要让你的 xpath [1] 在语法上正确(并且相对于 section 节点你将'in'):

    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
    

    瞧:

    A           B           C
    ----------- ----------- -----------
    987         654         321
    123         456         789
    

    【讨论】:

    • 谢谢!这就是缺失的部分。
    猜你喜欢
    • 1970-01-01
    • 2012-07-05
    • 1970-01-01
    • 2010-12-16
    • 1970-01-01
    • 1970-01-01
    • 2021-01-09
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多