define function snapshot( $e, $ts, $te ) { if (($e/date(@tstart) <= date($ts)) and ($e/date(@tend) >= date($ts)) and ($e/date(@tend) <= date($te))) then ( element mgrno { attribute tstart{$ts}, attribute tend{$e/@tend}, $e/text() } ) else if (($e/date(@tend) >= date($te)) and ($e/date(@tstart) >= date($ts)) and ($e/date(@tstart) <= date($te))) then ( element mgrno { attribute tstart{$e/@tstart}, attribute tend{$te}, $e/text() } ) else if (($e/date(@tstart) >= date($ts)) and ($e/date(@tend) <= date($te))) then ( element mgrno { attribute tstart{$e/@tstart}, attribute tend{$e/@tend}, $e/text() } ) else if (($e/date(@tstart) <= date($ts)) and ($e/date(@tend) >= date($te))) then ( element mgrno { attribute tstart{$ts}, attribute tend{$te}, $e/text() } ) else () } for $y in document('v-depts.xml')/departments/department return element department{$y/deptno, for $x in $y/mgrno return snapshot($x, '1994-05-06', '1995-05-06')}