crash
crash

Reputation: 69

Limiting the result to top four in xquery

<a>
{
for $o in doc("x.xml")/users/org
where fn:count($o/mem)
order by fn:count($o/mem) descending
return <org>
            <b> {$o/@name/string()} </b>
            <c> {$o/@ab/string()} </c>
            <d> {fn:count($o/mem)} </d>
       </org>
}
</a>

I have ordered the results in an descending order but I just need top 4 result from this. I tried to use the sub-sequence method on the wiki page and also the [position() 1,4] method to find the top 4 but was not successful.

Upvotes: 2

Views: 1028

Answers (1)

har07
har07

Reputation: 89305

One possible way using two for loops and limit the inner for to return only the first 4 results :

<a>
{
    for $p in
    (
        for $o in doc("x.xml")/users/org
        where fn:count($o/mem)
        order by fn:count($o/mem) descending
        return <org>
                    <b> {$o/@name/string()} </b>
                    <c> {$o/@ab/string()} </c>
                    <d> {fn:count($o/mem)} </d>
               </org>
    )[position() <= 4]
    return $p
}
</a>

update :

Turns out that we don't actually need the outer for :

<a>
{
    (
        for $o in doc("x.xml")/users/org
        where fn:count($o/mem)
        order by fn:count($o/mem) descending
        return <org>
                    <b> {$o/@name/string()} </b>
                    <c> {$o/@ab/string()} </c>
                    <d> {fn:count($o/mem)} </d>
               </org>
    )[position() <= 4]
}
</a>

Upvotes: 1

Related Questions