2

如何控制从 a 中选择的顺序for $x in (...)?在下面 XQuery 的最后一行中,我希望结果按 , 顺序排列$retmax$retmin但它以相反的顺序出现。

<result>
{
    let $max := max(doc("countries.xml")//country/(@population div @area))
    let $min := min(doc("countries.xml")//country/(@population div @area))
    for $country in doc("countries.xml")//country
    let $density := $country/(@population div @area)
    let $ret_min := if ($density = $min)
                    then <lowest density="{$density}">{data($country/@name)}</lowest>
                    else ()
    let $ret_max := if ($density = $max) 
                    then <highest density="{$density}">{data($country/@name)}</highest>
                    else ()
    for $r in ($ret_max, $ret_min) return $r
}   
</result>

产生:

  <result>
    <lowest density="0.026752619966905682">Greenland</lowest>
    <highest density="31052.3125">Macau</highest>
  </result>

但我想要:

  <result>
    <highest density="31052.3125">Macau</highest>
    <lowest density="0.026752619966905682">Greenland</lowest>
  </result>
4

1 回答 1

1

以下是我的写法...

let $ordered_countries := for $country in doc("countries.xml")//country
                          let $density := $country/(@population div @area)
                          order by $density 
                          return $country
let $low  := $ordered_countries[1]
let $high := $ordered_countries[fn:last()]
return (
    <lowest density="{$low/(@population div @area)}">{data($low/@name)}</lowest>,
    <highest density="{$high/(@population div @area)}">{data($high/@name)}</highest>
)
于 2012-07-29T09:00:08.927 回答