Skip to content
UoL CS Notes

Advanced XQuery

COMP207 Lectures

Order By

This clause is included in the following order:

Clause Requirement
for & let Any number, interleaved.
Some interpreters require at least one let.
where Optional
order by Optional
return Mandatory

and we can use it like so:

let $doc := doc("mydoc.xml")
for $b in $doc/books/book
for $author in $b/author
order by $author descending
return <pair>{$b/title}, {$author}</pair>

Group By

This clause is interted in the following order:

Clause Requirement
for & let Any number, interleaved.
Some interpreters require at least one let.
where Optional
group by Optional
order by Optional
return Mandatory

and we can use it like so:

let $doc := doc("mydoc.xml")
for $m in $doc/university/student/module
group by $mod:=$m
return <pair>{$mod}, {count($m)}</pair>

We can only aggregate by variables that are grouped (in this case only $m not $m/...).

Other aggregate functions include:

  • min()
  • max()
  • avg()
  • sum()

Distinct-Values

This converts the enclosed elements to strings, and filters so that they are distinct.

We can use it on each element $m in the for loop individually:

let $doc := doc("mydoc.xml")
for $m in $doc/university/student/module
return distinct-values($m)

This only removes duplicate module elements per-student.

or we can use it on the whole result:

distinct-values(let $doc := doc("mydoc.xml")
for $m in $doc/university/student/module
return $m)