有两个表:旅行和功能
TRIP
id_employee, date_start, date_end, original_function
001, '2016-04-01', '2016-04-30', 010
功能
id_employee, cd_Function, date_start_function, date_end_function
001, 023, '2016-04-04', '2016-04-10'
001, 015, '2016-04-13', '2016-04-25'
我需要生成以下报告:
员工:id_employee
Functions---Days
010-----------12
015-----------11
023-----------07
答案 0 :(得分:2)
我认为你基本上想要union all
两个表中的行然后进行聚合:
select id_employee, cd_function, sum(days) as days
from ((select id_employee, cd_function,
datediff(day, date_start_function, date_end_function) + 1 as days
from function
) union all
(select id_employee, original_function,
datediff(day, date_start, date_end) + 1 as days
from trip
)
) ft
group by id_employee;
答案 1 :(得分:0)
看起来应该从旅行原始功能的日子减去功能天数
select id_employee, cd_function, sum(days) as days
from
(select id_employee, original_function as cd_function,
datediff(day, date_start, date_end) + 1 as days
from trip
)
union all
(select f.id_employee, x.cd_function, x.days
from function f
left join trip t2 on t2.id_employee_id = f.employee_id
outer apply (
select f.cd_function, datediff(day, f.date_start_function, f.date_end_function) + 1 as days
union all
select t2.original_function as cd_function, -(datediff(day, f.date_start_function, f.date_end_function) + 1) as days
) x
)
group by id_employee, cd_function;