Group by
Output odd and even numbers
xquery version "3.0";
for $n in 1 to 10
group by $mod := $n mod 2
return
if ($mod = 0) then
<even>{$n}</even>
else
<odd>{$n}</odd>
Run full text search on Shakespeare and group results by speaker
xquery version "3.0";
let $query := "king"
for $speechBySpeaker in //SPEECH[ft:query(., $query)]
group by $speaker := $speechBySpeaker/SPEAKER
order by $speaker
return
<speaker name="{$speaker}">
{ $speechBySpeaker }
</speaker>
Group results by speaker and scene
xquery version "3.0";
let $query := "poison"
for $speechBySpeaker in //SPEECH[ft:query(., $query)]
group by $speaker := $speechBySpeaker/SPEAKER
order by $speaker
return
<ul>
<li>
<h3>{$speaker/text()}</h3>
<ul>
{
for $speech in $speechBySpeaker
group by $scene := $speech/ancestor::SCENE/TITLE
return
<li>
<h4>{$scene/text()}</h4>
<ul>
{
for $line in util:expand($speech)/LINE[exist:match]
return
<li>
{
for $node in $line/node()
return
typeswitch($node)
case element(exist:match) return
<mark>{$node/text()}</mark>
default return
$node
}
</li>
}
</ul>
</li>
}
</ul>
</li>
</ul>