Xquery - 查找每个组的最小属性。

时间:2016-04-03 21:20:48

标签: xpath xquery

我有一个XML文档,如下所示:

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

到目前为止,我只能使用min函数搞乱,但我最终只是将值与自身进行比较。

1 个答案:

答案 0 :(得分: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>

将XQuery 3 countorder by一起使用(效率最低):

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