3

我有 3 张桌子。第一个是人员名单:

桌子Personnel

Id_personnel         Name
1                    John
2                    Alice
3                    Tom
4                    Charles
5                    Ben

二是病假表:

桌子Medical

Id_personnel         Start_date         End_date
3                    2012-08-02         2012-08-05
2                    2012-08-02         2012-08-15
4                    2012-10-04         2012-10-06
2                    2012-10-02         2012-10-15
2                    2012-09-20         2012-09-21

三是放假表:

桌子Holiday

Id_personnel         Start_date         End_date
3                    2012-08-02         2012-08-05
2                    2012-02-02         2012-02-15
5                    2012-10-01         2012-10-05

我有两个活动日期:Symposium_start_date和一个(作为变量) ,Symposium_end_date我想选择所有可以参加研讨会(不在病假或假期)。Personnel.Id_personnelPersonnel.Name

在我的示例中,如果Symposium_start_date = 2012-10-02并且Symposium_end_date = 2012-10-06结果必须是:

Id_personnel         Name
1                    John
3                    Tom

(如您所见,爱丽丝和查尔斯正在休病假,本在度假)

谢谢!

4

3 回答 3

2

对于 MS SQL 服务器。

declare @start date = '2012-10-02', @end date = '2012-10-10'

select personnel.* 
from personnel
    left join holiday on personnel.Id_personnel = holiday.Id_personnel
        and holiday.start_date<=@end
        and holiday.end_date>=@start
    left join medical on personnel.Id_personnel= medical.Id_personnel
        and medical.start_date<=@end
        and medical.end_date>=@start
where holiday.Id_personnel is null  
and medical.Id_personnel is null
于 2012-10-08T08:55:20.727 回答
1

假设 MS-SQL,与其他类似,但显示了联合在一起的表,以及显示所有与研讨会日期冲突的子查询——我认为这更容易先写——然后选择所有不冲突的人。问候!

declare @Symposium_start_date date = '2012-10-02'
declare @Symposium_end_date date = '2012-10-06'

select * from Personnel P where p.Id_personnel not in (
    select Id_personnel from (
        select m.Id_personnel, m.Start_date, m.End_date
        from Medical M 
        union
        select h.Id_personnel, h.Start_date, h.End_date
        from Holiday H 
    ) as Leave
    where (Start_date  between @Symposium_start_date and @Symposium_end_date)
        or (End_date between @Symposium_start_date and @Symposium_end_date)
        or (Start_date <= @Symposium_start_date and End_date >= @Symposium_end_date)
)   
于 2012-10-08T09:20:25.357 回答
0

这仅是医疗表的示例。您可以轻松添加假期

declare @Symposium_start_date datetime
declare @Symposium_end_date  datetime

set @Symposium_start_date = '2012-08-01'
set @Symposium_end_date  = '2012-08-04'


select * 
from personel p left join medical m on p.Id_personel = m.Id_personel
where (@Symposium_start_date > m.end_date) or (@Symposium_end_date<m.start_date)
于 2012-10-08T08:58:57.423 回答