【问题标题】:How to group elements by attribute values using XQuery on SQL Server?如何在 SQL Server 上使用 XQuery 按属性值对元素进行分组?
【发布时间】:2010-01-28 21:51:43
【问题描述】:

假设我在 SQL Server 中有一个表,其中包含带有内部连接的查询的结果。

以下 XQuery:

select @code.query
(
'for $s in /root/row
return 
<Foo Language="{data($s/@lang)}" Method="{data($s/@method)}" Returns="{data($s/@returnType)}">
<Bar ReferencedBy="{data($s/@callers)}" Static="{data($s/@static)}" />
</Foo>'
)

及其结果:

<Foo Language="C#" Method="getFoos" Returns="FooCollection">
  <Bar ReferencedBy="Baz" Static="true" />
</Foo>
<Foo Language="C#" Method="getFoos" Returns="FooCollection">
  <Bar ReferencedBy="Bar" Static="false" />
</Foo>

其实我想要的是:

<Foo Language="C#" Method="getFoos" Returns="FooCollection">
  <Bar ReferencedBy="Baz" Static="true" />
  <Bar ReferencedBy="Bar" Static="false" />
</Foo>

为了避免求助于 LINQ 和哈希表,使用 XQuery 执行此操作的最佳方法是什么?

【问题讨论】:

  • 看起来您需要在 FOO 标记内使用 for 循环来迭代您要填充的 BAR 值。

标签: sql-server xml group-by xquery


【解决方案1】:

在构造结果之前,您需要使用每种语言、方法和返回值枚举所有节点

for $lang in distinct-values(/root/row/@lang)
let $nodes := /root/row[@lang=$lang]
for $method in distinct-values($nodes/@method)
let $nodes := $nodes[@method=$method]
for $return in distinct-values($nodes/@returnType)
let $nodes := $nodes[@returnType=$returnType]
return
  <Foo Language="{$lang}"
       Method="{$method}"
       Returns="{$returnType}">
  {
    for $bar in $nodes
    return 
    <Bar ReferencedBy="{data($node/@callers)}"
         Static="{data($node/@static)}" />
  }
  </Foo>

我自己不使用 SQL Server,所以我不能保证这会起作用,但它是一个有效的 XQuery 解决方案。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-02-21
    • 1970-01-01
    • 2017-03-18
    • 1970-01-01
    • 1970-01-01
    • 2010-10-03
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多