简体   繁体   English

如何在SQL Server上使用XQuery按属性值对元素进行分组?

[英]How to group elements by attribute values using XQuery on SQL Server?

Let's say I have a table in SQL Server which contains the results of a query with an inner join. 假设我在SQL Server中有一个表,其中包含带有内部联接的查询的结果。

The following XQuery: 以下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>'
)

And its result: 其结果是:

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

What I would like in fact is the following: 我实际上想要的是以下内容:

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

What's the best way to do this using XQuery in order to avoid resorting to LINQ and a hash table? 为了避免诉诸LINQ和哈希表,使用XQuery做到这一点的最佳方法是什么?

You need to enumerate over all nodes with each language, method and return value before constructing the results 在构造结果之前,需要使用每种语言,方法和返回值枚举所有节点

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>

I do not use SQL Server myself, so I can't guarantee that this will work, but it is a valid XQuery solution. 我自己没有使用SQL Server,所以不能保证这会起作用,但这是有效的XQuery解决方案。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM