define function employeeIn ($deptno, $ts, $te) { if (date($ts) <= date('2002-03-24')) then ( for $x in document('v-emps.xml')/employees/employee where $x/deptno/text() = $deptno and (($x/deptno/date(@tstart) >= date('2002-03-24') and $x/deptno/date(@tstart) <= date($te)) or ($x/deptno/date(@tend) >= date('2002-03-24') and $x/deptno/date(@tend) <= date($te)) or ($x/deptno/date(@tend) >= date($te) and $x/deptno/date(@tstart) <= date('2002-03-24'))) return $x ) else ( for $x in document('v-emps.xml')/employees/employee where $x/deptno/text() = $deptno and (($x/deptno/date(@tstart) >= date($ts) and $x/deptno/date(@tstart) <= date($te)) or ($x/deptno/date(@tend) >= date($ts) and $x/deptno/date(@tend) <= date($te)) or ($x/deptno/date(@tend) >= date($te) and $x/deptno/date(@tstart) <= date($ts))) return $x ) } for $y in document('v-depts.xml')/departments/department/mgrno where $y/date(@tstart) >= date('2002-03-24') or ($y/date(@tstart) <= date('2002-03-24') and $y/date(@tend) >= date('2002-03-24')) return( element manager{ $y, element counting{count(employeeIn($y/../deptno/text(),$y/@tstart,$y/@tend))} } )