选择范围之间的数据

时间:2017-05-30 07:55:38

标签: sql oracle select

进入Oracle DB我有两个表,表A和表B,

表B有一系列日期,我必须找出表A中的年份是在开始日期之前,在完成日期之后还是在不在范围内

TABLE A
+-----+-----+
|NAME |YEAR |
+-----+------
|R1   |2016 |
|R1   |2015 |
|R1   |2014 |
|R1   |2013 |
|R2   |2016 |
|R2   |2015 |
|R2   |2014 |
|R2   |2013 |
+-----+-----+

TABLE B
+----+---------+----------+
|NAME|YEARSTART|YEARFINISH|
+----+---------+----------+
|R1  |2015     |2016      |
|R1  |2013     |2013      |
|R2  |2016     |2016      |
|R2  |2013     |2014      |
+----+---------+----------+


RESULT
+----+----+
|NAME|YEAR|
+----+----+
|R1  |2014|
|R2  |2015|
+----+----+

我发现记录在较低的开始日期之前和最高的完成日期之后

但如何找出一年不在范围内?

在我的例子中,我得到了R1 2014和R2 2015不在范围内,如何识别它们?

2 个答案:

答案 0 :(得分:2)

使用左连接:

SELECT *
FROM TableA a
LEFT JOIN TableB b ON a.NAME = b.NAME 
                  AND a.YEAR >= b.YEARSTART 
                  AND a.YEAR <= b.YEARFINISH
WHERE b.NAME IS NULL

答案 1 :(得分:1)

如果表b中不存在重叠年份相同的名称,您可以使用NOT EXISTS从表A返回一行:

select ta.name, ta.year
from tablea ta
where not exists (select 1 from tableb tb
                  where ta.name = tb.name
                    and ta.year between tb.yearstart and tb.yearend)