Search code examples
xpathxqueryxpath-2.0xquery-3.0

XQuery/XPath LIMIT a sum


I am new to XQuery. I need to limit by 1 in XQuery but I'm having trouble.

I am trying to find out the winner of a tournament by finding each players scores and summing up the scores to get the total scores. I then sort in descending order and try to limit the total score, however I am having problems with trying to limit in XQuery.

Here I am wanting to get the top score but I have tried to use subsequence($sequence, $starting-item, $number-of-items) and [position()] but it seems to not be working.

for $pair_ids in distinct-values(fn:doc("tourny.xml")/Competition[@date = "2012-12-12"]/Tennis/Partner/@pair_id)
let $total_scores := sum(fn:doc("tourny.xml")/Competition[@date = "2012-12-12"]/Tennis/Partner[@pair_id = $pair_ids]/@score)
order by $total_scores descending
return 
    $total_scores

the output is giving me:

$total_scores:
34
11
20

How can I limit the result so I only get 34 as the highest score? Thanks


Solution

  • You can use fn:max() function as follow:

    fn:max(
    for $pair_ids in distinct-values(fn:doc("tourny.xml")/Competition[@date = "2012-12-12"]/Tennis/Partner/@pair_id)
    let $total_scores := sum(fn:doc("tourny.xml")/Competition[@date = "2012-12-12"]/Tennis/Partner[@pair_id = $pair_ids]/@score)
    order by $total_scores descending
    return $total_scores
    )