访问查询以返回在日期范围之间找不到的记录

时间:2019-02-25 14:59:38

标签: sql ms-access

我有以下示例数据

Table1      
REF_NO  SUPP_START_DATE SUPP_END_DATE
123     01/01/2018      31/12/2018
456     01/01/2017      31/12/2017
789     01/01/2016      31/12/2016

Table2      
REF_NO  CHG_START_DATE  CHG_END_DATE
123     01/03/2018      31/03/2018
123     01/04/2018      30/04/2018
456     01/02/2018      28/02/2018
456     01/01/2017      31/01/2017
789     01/07/2016      31/07/2016

我想知道是否有可能在Access SQL中返回所有不在table1的开始日期和结束日期之间的费用(table2)。因此,使用上面的示例数据,将返回以下内容:-

Results     
REF_NO  CHG_START_DATE  CHG_END_DATE
456     01/02/2018      28/02/2018

我知道如何使用

联接两个表
SELECT table1.ref_no, table2.CHG_START_DATE, table2.CHG_END_DATE
FROM table1 
LEFT JOIN table2 ON table1.ref_no = table2.ref_no

但是我不确定如何解决日期不匹配

2 个答案:

答案 0 :(得分:2)

如果仅查看开始和结束日期就足够了:

select t2.*
from table2 t2
where not exists (select 1
                  from table1 as t1
                  where t1.refno = t2.refno and
                        t2.CHG_START_DATE between UPP_START_DATE and SUPP_END_DATE
                 ) or
      not exists (select 1
                  from table1 as t1
                  where t1.refno = t2.refno and
                        t2.CHG_END_DATE between UPP_START_DATE and SUPP_END_DATE
                 ) ;

答案 1 :(得分:0)

这是使用联接而不是相关子查询的另一种方法:

select t2.* from table1 t1 inner join table2 t2 on t1.ref_no = t2.ref_no 
where not
(
    (t2.chg_start_date between t1.supp_start_date and t1.supp_end_date) and
    (t2.chg_end_date   between t1.supp_start_date and t1.supp_end_date)
)