# [xquery-talk] find most occurring incidence

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

```And two another solutions, taking advantage of maps:

let \$map := map:merge(
for \$color in //color
group by \$value := \$color
return map { \$value: count(\$color) }
)
let \$max := max(\$map?*)
return map:for-each(\$map, function(\$color, \$value) {
if(\$value eq \$max) then \$color else ()
})

The more cryptical (and not that efficient) one:

let \$m := map:merge(
for \$v in distinct-values(//color)
return map { \$v: count(//color[. eq \$v]) }
)
return map:keys(\$m)[\$m(.) = max(\$m?*)]

On Tue, Apr 26, 2016 at 12:17 PM, Christian Grün
<christian.gruen at gmail.com> wrote:
> Hi Leo,
>
> here’s one more solution. It is not much shorter than yours, but may
> be a bit more readable:
>
>   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?
>>