SQL 删除两个表之间的时间重叠
SQL to remove time overlaps between two tables
我有两个 table。每个 table 有两个字段:from_date
和 to_date
。我需要找到 table A
中不与 table B
中的记录重叠的所有记录。
我正在使用 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')
结果应该只是TableA(1200-1300)中的第三条记录,因为它不与TableB中的任何记录重叠。
如果您不想重叠,可以采用以下一种方法:
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
);
我有两个 table。每个 table 有两个字段:from_date
和 to_date
。我需要找到 table A
中不与 table B
中的记录重叠的所有记录。
我正在使用 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')
结果应该只是TableA(1200-1300)中的第三条记录,因为它不与TableB中的任何记录重叠。
如果您不想重叠,可以采用以下一种方法:
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
);