define function calAverage ($instance) { for $x in document('v-emps.xml')/employees/employee/salary let $value := int($x/text()) where $x/date(@tstart) <= date($instance) and $x/date(@tend) > date($instance) return $value } define function allDate() { for $x in document('v-emps.xml')/employees/employee/salary return $x sortby (@tstart ascending) } for $snapshot in distinct-values(allDate()/@tstart) return element average { avg(calAverage($snapshot)), attribute tstart{$snapshot} }