Roaid
Roaid

Reputation: 314

XQuery: find max value and return relevant information

I have a XML file containing elements with the following structure:

<listing>
    <auction_info>
        <num_bids>29</num_bids>
    </auction_info>
    <item_info>
        <result>item A</result>
    </item_info>
</listing>
<listing>
    <auction_info>
        <num_bids>12</num_bids>
    </auction_info>
    <item_info>
        <result>item B</result>
    </item_info>
</listing>

I need a query to calculate the max of num_bids and return the result.In my example,the num_bids 29 is the max number,so need return item A.But in my code below,it returned all results.

let $x := //listing
let $max := max($x/auction_info/num_bids)
return $x[//num_bids = $max]/item_info/result

Thank you for help.

Upvotes: 0

Views: 3768

Answers (1)

Florent Georges
Florent Georges

Reputation: 2327

What your expression asks for is "give me all $x where there is a num_bids, anywhere in the document, which is equal to $max." Which is different than "give me all $x for which its own num_bids is equal to $max." The following should do (not tested):

let $in  := //listing
let $max := max($in/auction_info/num_bids)
return
   $in[auction_info/num_bids eq $max]/item_info/result

If you really want to use the descendant axis, you can change $x[//xxx] to $x[.//xxx] (see the extra dot?) The first one says "for each $x, any xxx descendant from its root," the second says "for each $x, any xxx descendant from itself." But from your example input, the query above is most likely what you want.

Upvotes: 4

Related Questions