user6030673
user6030673

Reputation:

XQuery 3.0 equivalent group by in xquery 1.0 version

I have the following code, and the saxon jar file I have cannot read xquery 3.0.

for $item in doc("order.xml")//item
group by $d := $item/@dept
order by $d
return 
  <department totalQuantity="{sum($item/@quantity)}"
              code="{$d}"
              numItems="{count($item)}"/>

The output displays the department, totalQuantity, and the number of items. It's supposed to be grouped by the code, the code above doesn't compile.

I was hoping theres a way that would work with xquery 1.0

Upvotes: 3

Views: 783

Answers (1)

Joe Wicentowski
Joe Wicentowski

Reputation: 5294

Typically the XQuery 1.0 equivalent of a XQuery 3.0 "group by"-enhanced FLWOR expression relies on the fn:distinct-values() function to find the distinct keys for grouping your items together. Having found the keys, you can simply iterate through the keys with an XQuery 1.0 FLWOR expression and select the items with the matching key. Here is the XQuery 1.0 equivalent of your query:

let $items := doc("order.xml")//item
let $depts := distinct-values($items/@dept)
for $dept in $depts
let $dept-items := $items[@dept eq $dept]
order by $dept
return
    <department totalQuantity="{sum($dept-items/@quantity)}"
                code="{$dept}"
                numItems="{count($dept-items)}"/>

Upvotes: 5

Related Questions