sql - 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
并检查您的解决方案中的计数。这仅检测相同日期的多个条目。希望你能提出一些建议。再次感谢
解决方案
我认为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'
);
推荐阅读
- docker - 纱线工作区和泊坞窗
- java - 让 Mockito 1.x 在前 N 次调用中抛出异常,然后返回一个值?
- powershell - Powershell - 如何使用 $List.convertAll() 或替代 C# 方法来克隆列表
- angular - Angular 5,这是什么?(帮助识别被误解的代码)
- r - 使用 read_csv 创建循环函数 - RStudio
- excel - Excel 公式计算组中的所有项目以查看状态是否为打开状态
- python-3.x - 有没有办法减小 Spacy 安装的大小?
- exception - java尝试捕获多个方法
- android - android - recyclerview - 获取位图
- loadrunner - 如何在 vugen/load runner 中捕获/记录评级(星)