let $distinct-countries := distinct-values(?cities?*?country)
return
map:merge(
for $country in $distinct-countries
return
let $group := ?cities?*[?country = $country]
return
map {
$country : map {
"cities" : $group?name,
"population" : sum($group?pop)
}
}
)