3

有两张Leaves, Attendanceatd数据表。

我需要在这两个表中显示不同的ListofDates和具有某些条件的表,即在表 Date 列上的 Leave table approvalstatus='Approved'startdate / enddate期间持续时间。employeeid

表架构: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

4

3 回答 3

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 自动应用 DISTINCT(如果您使用 UNION ALL,请注意区别)

更新了 SQLFiddle

于 2013-05-27T10:21:30.160 回答
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 排序。总是去执行计划检查性能。

于 2013-05-27T10:26:55.853 回答
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
于 2013-05-27T10:29:41.347 回答