Aggregating values
File: Data.xml <employees> <employee name="James" salary="1234" yearServed="1" location="North"/> <employee name="Joe" salary="3211" yearServed="2" location="South"/> <employee name="Jod" salary="3422" yearServed="3" location="North"/> <employee name="Jason" salary="1321" yearServed="4" location="East"/> <employee name="Jack" salary="2324" yearServed="3" location="North"/> <employee name="Jeep" salary="4321" yearServed="2" location="East"/> <employee name="Jane" salary="2344" yearServed="1" location="South"/> </employees> File: Query.xquery for $d in distinct-values(doc("Data.xml")//employee/@location) let $employees := doc("Data.xml")//employee[@location= $d] order by $d return <department name="{$d}" total="{sum($employees/@yearServed)}"/> Output: <?xml version="1.0" encoding="UTF-8"?> <department total="6" name="East"/> <department total="7" name="North"/> <department total="3" name="South"/>