Arpan C
Arpan C

Reputation: 13

How to order by specific value first in xquery?

How to order by specific value first in xQuery?

Example:

<xml>
    <b>
        <msg>A</msg>
        <val>5</val>
    </b>
    <b>
        <msg>B</msg>
        <val>1</val>
    </b>
    <b>
        <msg>C</msg>
        <val>3</val>
    </b>
    <b>
        <msg>K</msg>
        <val>2</val>
    </b>
    <b>
        <msg>D</msg>
        <val>3</val>
    </b>
</xml>

I want to get based on the ordered value but value should be 3 to be first in the list.

Upvotes: 0

Views: 281

Answers (3)

Arpan C
Arpan C

Reputation: 13

As suggested by Ewout Graswinckel, I followed the steps. It worked. Thanks a lot.

We can order by more "based-on-condition" by adding ","

such as like this - 

(for $x in (doc('')) 
 order by if ($x//val = 3) then (0) else (1), 
    if (contains($x//msg, 'A')) then (0) else (1)
return $x 
 )

So after val = 3 , next order by will be anything which contains 'A'.

Upvotes: 0

Jens Erat
Jens Erat

Reputation: 38682

It seems your values are all in the set of natural numbers. Then, you could select a value which is smaller than all other values in the natural numbers -- for example, -1. If the value is 3, replace it for ranking by -1, otherwise use the normal value.

for $b in //b
let $rank := if ($b/val = 3) then -1 else $b/val/number()
order by $rank ascending
return $b

You didn't give any hint on expected output. If you only want the numbers or whatever output, just modify the return statement.

Upvotes: 2

Ewout Graswinckel
Ewout Graswinckel

Reputation: 1273

You can write an expression in your order by clause so you could do something like this (there might be nicer ways though):

for $b in //b
order by if ($b/val = 3) then (0) else (1), $b/msg 
return $b

Upvotes: 3

Related Questions