首页 > 解决方案 > sql在日期范围内查找

问题描述

假设我们有两张桌子

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.

能不能做到。如果是这样的话。

提前感谢您的帮助...

编辑:@戈登。假设表 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

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

标签: sqlpostgresqlpostgresql-9.4

解决方案


我认为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'
                 );

推荐阅读