xquery version '1.0'; { let $part := xs:integer() let $resource := let $uniqueid := let $allparts := ( for $exercise in doc($resource)/*/exercise[ variables/uniqueid = $uniqueid ] order by xs:dateTime($exercise/dateTime) return $exercise ) let $numparts := count($allparts) let $newpart := min((max(($part,1)),$numparts)) let $nextpart := min(($newpart + 1, $numparts)) return ( $allparts[$newpart], { $numparts } , { $newpart } , if ($newpart lt $numparts) then { $allparts[$nextpart] } else () ) }