sql 在日期范围内查找

sql find within daterange

假设我们有两个 table

Table A:
col_1,   col_2,   col_3,   col4
04/04/2017 1800.00  200.00 B123
21/04/2017 1800.00  200.00 B123
14/09/2017 1200.00  300.00 B123
18/12/2017 1100.00  150.00 B123
21/01/2018 1100.00  150.00 B123
06/05/2017 2400.00  500.00 A345



Table B:
col_1,   col_2,   col_3,  col4
05/04/2017 1800.00,  200.00 B123
12/09/2017 1200.00,  300.00 B123
20/12/2017 1100.00,  150.00 B123
08/05/2017 2400.00   500.00 A345

我想做类似

的事情
select * from A 
where (col_1, col_2, col_3, col_4) 
    not in (select +/- 2 days_of_col_1, col_2, col_3, col_4 from B.

可以吗。如果是这样的话。

在此先感谢您的帮助...

编辑:@Gordon。 说 table A 有如下额外的行

05/04/2017 1800.00  200.00 B123
05/04/2017 1800.00  200.00 B123
06/04/2017 1800.00  200.00 B123

这将被标记为存在。我尝试使用

count (*) OVER (PARTITION BY col_1, col_2 ORDER BY col_1, col_2)  AS count_col_2,
count (*) OVER (PARTITION BY col_1, col_2 ORDER BY col_1, col_3)  AS count_col_3

并检查您的解决方案中的计数。这仅检测相同日期的多个条目。 希望你能提出一些建议。 再次感谢

我认为 not exists 是你最好的选择:

select a.*
from a
where not exists (select 1
                  from b
                  where b.col_2 = a.col_2 and b.col_3 = a.col_3 and b.col_4 = a.col_4 and
                        a.col_1 >= b.col_1 - interval '2 day' and
                        a.col_1 <= b.col_1 + interval '2 day'
                 );

我认为这样的方法也可以:

 select * from A a
 left join B b
 on a.col_1 between dateadd(-2, dd, b.col_1) and dateadd(2, dd, b.col_1)
 and a.col_2 between dateadd(-2, dd, b.col_2) and dateadd(2, dd, b.col_2)
 and a.col_3 between dateadd(-2, dd, b.col_3) and dateadd(2, dd, b.col_3)
 and a.col_4 between dateadd(-2, dd, b.col_4) and dateadd(2, dd, b.col_4)
 where b.col_1 is null