xquery version "3.1" encoding "UTF-8";
declare variable $doc := doc("factbook.xml");
element Memberships {
let $membershipPotentcy := function($orgs){if (count($orgs)le 0) then 'none'
else if (count($orgs) le 5) then 'few'
else 'many'}
let $organizations := function($country){$doc//organization[members/@country = $country/@id]/@abbrev/string(.)}
for $countries in $doc//country
group by $mp:= $membershipPotentcy($organizations($countries))
order by $mp
return
element {$mp} {
for $country in $countries
let $organizations := function($country){$doc//organization[members/@country = $country/@id]/@abbrev/string(.)}
order by $country/@name
return
<country>{$country/@name, $organizations($country)}</country>
}}