有两个表Leaves, Attendanceatd
包含数据。
我需要在这两个表格中显示不同的ListofDates
和employeeid
,其条件是在离开表 approvalstatus ='已批准' 中表格日期列上的 startdate / enddate 期限持续时间。
表架构: SQL FIDDLE
create table Leaves(idemp_lv int,leavedate Datetime, approvalstatus varchar(100))
insert into Leaves values (1,'2013-04-22 00:00:00.000','Approved');
insert into Leaves values (2,'2013-04-21 00:00:00.000','Approved');
insert into Leaves values(3,'2013-04-26 00:00:00.000','Approved');
insert into Leaves values(1,'2013-04-21 00:00:00.000','Pending');
insert into Leaves values(3,'2013-04-02 00:00:00.000','Pending');
insert into Leaves values(1,'2013-04-19 00:00:00.000','Approved');
create table Attendanceatd(idemp_at int,absentdate Datetime)
insert into Attendanceatd values(1,'2013-04-19 00:00:00.000');
insert into Attendanceatd values(3,'2013-04-02 00:00:00.000');
insert into Attendanceatd values(1,'2013-04-15 00:00:00.000');
期望的输出:
Empid ListofDate
1 2013-04-22 00:00:00.000
1 2013-04-19 00:00:00.000
1 2013-04-15 00:00:00.000
2 2013-04-21 00:00:00.000
3 2013-04-26 00:00:00.000
3 2013-04-02 00:00:00.000
目前我正在尝试这个:
select ListOfDates
from
(
select leavedate as ListOfDates from leaves where approvalstatus='Approved' and leavedate >='20130302' and leavedate <'20130501'
union
select absentdate as ListOfDates from Attendanceatd where absentdate >='20130302' and absentdate <'20130501'
)t1
group by ListOfDates
无法与 ListOfDates一起 employeeId
答案 0 :(得分:3)
我认为你不需要分组。这给了你想要的东西
select idemp_lv, leavedate as ListOfDates
from leaves
where approvalstatus='Approved' and leavedate >='20130302' and leavedate <'20130501'
union
select idemp_at, absentdate as ListOfDates
from Attendanceatd
where absentdate >='20130302' and absentdate <'20130501'
自动UNION applies DISTINCT(注意使用UNION ALL时的区别)
答案 1 :(得分:1)
select distinct empid, ListOfDates
from
(
select idemp_lv as empid, leavedate as ListOfDates from leaves where approvalstatus='Approved' and leavedate >='20130302' and leavedate <'20130501'
union all
select idemp_at as empid, absentdate as ListOfDates from Attendanceatd where absentdate >='20130302' and absentdate <'20130501'
)t1
group by empid, ListOfDates
除非我遗漏了某些东西,否则应该这样做。请记住,union all会更快,但会导致更加麻烦的sql排序。始终执行执行计划以检查性能。
答案 2 :(得分:1)
select EmpId,ListOfDates
from
(
select idemp_lv as EmpId ,leavedate as ListOfDates from leaves where approvalstatus='Approved'
union all
select idemp_at as EmpId , absentdate as ListOfDates from Attendanceatd
)T1
where ListOfDates between '2013-03-02' and '2013-05-01'
group by EmpId,ListOfDates