# [xquery-talk] find most occurring incidence

Christian Grün christian.gruen at gmail.com
Tue Apr 26 03:17:04 PDT 2016

```Hi Leo,

here’s one more solution. It is not much shorter than yours, but may

let \$cols :=
for \$colors in //color
group by \$value := \$colors/data()
return <color count="{ count(\$colors) }" value="{ \$value }"/>
let \$max := max(\$cols/@count)
return \$cols[@count = \$max]/@value/data()

I think that in every case the values need to be accessed at least
twice, because we’ll first need to find out what is the actual maximum
count, and then need to look for all values matching that maximum.

Hope this helps,
Christian

On Tue, Apr 26, 2016 at 12:02 PM, Leo Studer <leo.studer at varioweb.ch> wrote:
> Hello Cracks ;-)
>
> I need to find the most occurring incidence, lets say the color that occurs
> most out of
>
> <colors>
>     <color>red</color>
>     <color>green</color>
>     <color>blue</color>
>     <color>red</color>
>     <color>green</color>
>     <color>green</color>
>     <color>red</color>
>     <color>blue</color>
>    <!-- .... -->
> </colors>
>
>
> Here my first solution
>
> (for \$color in distinct-values(//color)
> order by count(//color[. eq \$color]) descending
> return \$color)[1]
>
> Problem: red and green have both 3 occurrences.
>
> This works but looks horrible
>
> for \$max in max(for \$color in distinct-values(//color) return
> count(//color[. eq \$color])),
> \$color in distinct-values(//color)
> return
> if (count(//color[. eq \$color]) eq \$max) then \$color else ()
>
>
> Any better suggestions?
>