(: Temporal Join. For each employee, show his/her title history and his/her manager history. :) declare function local:overlap($a, $ts,$te) { if (xs:date($a/@tstart) <= xs:date($ts) and xs:date($a/@tend) >= xs:date($te)) then ( element mgrno { attribute tstart{$ts}, attribute tend{$te}, $a/text() }) else if (xs:date($a/@tstart) <= xs:date($ts) and (xs:date($a/@tend)) >= xs:date($ts) and (xs:date($a/@tend)) <= xs:date($te)) then ( element mgrno { attribute tstart{$ts}, attribute tend{$a/@tend}, $a/text() }) else if (($a/xs:date(@tend) >= xs:date($te)) and ($a/xs:date(@tstart) >= xs:date($ts)) and ($a/xs:date(@tstart) <= xs:date($te))) then ( element mgrno { attribute tstart{$a/@tstart}, attribute tend{$te}, $a/text() } ) else if (($a/xs:date(@tstart) >= xs:date($ts)) and ($a/xs:date(@tend) <= xs:date($te))) then ( element mgrno { attribute tstart{$a/@tstart}, attribute tend{$a/@tend}, $a/text() } ) else () }; declare function local:final() { for $r in doc("v-emps.xml")/employees/employee for $m in doc("v-depts.xml")/departments /department[deptno=$r/deptno] let $ov := local:overlap($r/deptno, $m/mgrno/@tstart, $m/mgrno/@tend) return (element emp{$r/empno, $r/title, $r/deptno, for $e_temp in $r/deptno for $m_temp in $m/mgrno let $ov := local:overlap($e_temp, $m_temp/@tstart, $m_temp/@tend) where not (empty($ov)) return $m_temp}) }; let $f := local:final() return element all_emps{$f}