2016-04-03 33 views
1

我有,看起來像一個XML文檔:Xquery - 查找每個組的最小屬性。

<charities> 
    <charity char_id="x211x"> 
     <donor type="other" amount="300" /> 
     <donor type="corporation" amount="250" /> 
     <donor type="individual" amount="50" /> 
    </charity> 
    <charity char_id="x202x"> 
     <donor type"other" amount="25" /> 
     <donor type="individual" amount="25" /> 
     <donor type="corporation" amount="500" /> 
    </charity> 
</charities> 

我希望能夠使用XQuery返回最低捐款爲每個慈善事業,與慈善機構的ID和捐贈金額。哪裏有聯繫最小,兩者都報道

所以結果就在這種情況下,像這樣:

<minDonors> 
    <charity char_id="x211x"> 
     <donation amount="50">individual</donation> 
    </charity> 
    <charity char_id="x202x"> 
     <donation amount="25">other</donation> 
     <donation amount="25">individual</donation> 
    </charity> 
</minDonors> 

到目前爲止,我只能用最小功能,但我的一個爛攤子獲得通過只是最終將價值與自身進行比較。

回答

1

使用min(...)

<minDonors>{ 
    for $charity in //charity 
    let $min-donation := min($charity/donor/@amount/number()) 
    return <charity>{ 
    $charity/@char_id, 
    for $donor in $charity/donor[@amount = $min-donation] 
    return <donation amount="{$donor/@amount}">{ 
     $donor/@type/string() 
    }</donation> 
    }</charity> 
}</minDonors> 

order by使用XQuery 3 count在一起(最有可能效率較低):

<minDonors>{ 
    for $charity in //charity 
    return <charity>{ 
    $charity/@char_id, 
    for $donor in $charity/donor 
    group by $amount := $donor/@amount 
    order by xs:double($amount) 
    count $c 
    where $c = 1 
    for $donation in $donor 
    return <donation amount="{$amount}">{ 
     $donation/@type/string() 
    }</donation> 
    }</charity> 
}</minDonors>