xpathxqueryzorba

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.


Solution

  • 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>