As Daniel Haley suggested, you should do it the other way round, i.e. iterating over each title and looking for the authors which write this specific title. You can use distinct-values
or group by
. The following should work:
<bib>
{
let $titles := distinct-values(doc('test')//title)
for $t in $titles
let $authors := doc('test')//author[title = $t]
order by count($authors)
return
<book authors="{count($authors)}">
<title>{$t}</title>
{
for $a in $authors
order by $a/name
return <author>{$a/name/string()}</author>
}
</book>
}
</bib>