2016-09-27 122 views
0

我有两个表。每个表格有两个字段:from_dateto_date。我需要找到table A中的所有记录,这些记录不会与table B中的记录重叠。SQL删除两个表之间的时间重叠

我使用MSSQL 2008年

CREATE TABLE Table_A(from_date datetime , to_date datetime) 

CREATE TABLE Table_B(from_date datetime , to_date datetime) 

Insert into Table_A (from_date, to_date) values ('2016-09-01 10:00:00','2016-09-01 11:00:00') 

Insert into Table_A (from_date, to_date) values ('2016-09-01 11:00:00','2016-09-01 12:00:00') 

Insert into Table_A (from_date, to_date) values ('2016-09-01 12:00:00','2016-09-01 13:00:00') 

Insert into Table_B (from_date, to_date) values ('2016-09-01 10:00:00','2016-09-01 12:00:00') 

Insert into Table_B (from_date, to_date) values ('2016-09-01 13:00:00','2016-09-01 14:00:00') 

Insert into Table_B (from_date, to_date) values ('2016-09-01 14:00:00','2016-09-01 15:00:00') 

结果应该是仅在表A(1200-1300)第三条记录,因为它不如果你在表重叠的任何记录B.

回答

1

想要没有重叠,那么这里是一种方式:

select a.* 
from table_a a 
where not exists (select 1 
        from table_b b 
        where a.from_date < b.to_date and a.to_date > b.from_date 
       ); 
+0

丢失了table_b的别名。 – p2k

+0

完全加入有什么问题? – ajeh