2010-01-28 121 views
0

比方說,我在SQL Server中有一個表,其中包含帶內連接的查詢結果。如何在SQL Server上使用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>' 
) 

而其結果是:

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

什麼是做到這一點的最好辦法使用XQuery以避免使用LINQ和哈希表?

+0

看起來您需要在FOO標記內部使用for循環來迭代要填充的BAR值。 – 2010-01-28 22:01:33

回答

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解決方案。

相關問題