SQL - 比较两个日期范围表时查找非重叠日

时间:2017-11-29 14:15:48

标签: sql-server

我正在使用Microsoft SQL Server 2018.我有两个包含日期范围的表。其中一个员工ID和工作日期以及另一个员工ID和工作日期。每个工作日都需要有相应的工作日期,但我需要找到没有工作日期的工作日。

Table 1    
Row, EmployID, EmployStart, EmployEnd
1   1   1/1/2016    12/31/2016
2   1   1/1/2017    12/31/2017
3   1   1/1/2018    12/31/2018
4   2   1/1/2016    12/31/2016
5   2   1/1/2017    12/31/2017
6   2   1/1/2018    12/31/2018              
7   3   1/1/2016    12/31/2016
8   3   1/1/2017    12/31/2017
9   3   1/1/2018    12/31/2018              
10  4   1/1/2016    12/31/2016
11  4   1/1/2017    12/31/2017
12  4   1/1/2018    12/31/2018              
13  5   1/1/2016    12/31/2016
14  5   1/1/2017    12/31/2017
15  5   1/1/2018    12/31/2018

Table 2
Row EmployID    WorkStart   WorkEnd
1   1   1/1/2016    12/31/2016
2   1   1/1/2017    12/31/2017
3   1   1/1/2018    12/31/2018  
4   2   1/1/2016    12/31/2016
5   2   1/1/2017    12/31/2017                      
6   3   1/1/2016    12/31/2016
7   3   1/1/2017    12/31/2017
8   3   1/1/2018    6/30/2018       
9   4   1/1/2016    12/31/2016
10  4   5/1/2017    12/31/2017
11  4   1/1/2018    12/31/2018
12  5   1/1/2016    12/31/2016
13  5   1/1/2017    12/31/2017
14  5   1/1/2018    12/31/2018

因此,在这个数据集中,我想要调出表1中的第6,9和11行,因为有没有工作日期的就业日期。然后结果只是没有工作的日期。

所以结果看起来像

Row EmployID    MissStart   MissEnd
1   2      1/1/2018    12/31/2018
2   3      7/1/2018    12/31/2018
3   4      1/1/2017    4/30/2017

我目前有这个

select *
from table1 a
left join table2 b
    on a.employid = b.employid
    and (
        cast(a.employstart as date)between cast(b.workstart as date) and cast(b.workend as date)
        or cast(a.employend as date)between cast(b.workstart as date) and cast(b.workend as date)
        )
where b.employid is null

1 个答案:

答案 0 :(得分:0)

检查重叠

Determine Whether Two Date Ranges Overlap

select *
from table1 a
left join table2 b
    on a.employid = b.employid
    and (   cast(a.employstart as date) <= cast(b.workend as date) 
        and cast(a.employend as date) >= cast(b.workstart as date) 
        )
where b.employid is null