查找仅在给定日期 (SQL) 之前的记录

Finding records that are only before a given date (SQL)

我尝试了多个查询,但 none 都有效。 这可能真的很简单。

这是一个例子 table :

ordernr debnaam     debnr   orddat
1       Coca-Cola   123     2019-02-07
12      Altec       456     2019-02-07
123     Coca-Cola   123     2016-01-01
1234    Brady       789     2015-03-18

因此,重点是找到自过去 2 年以来未订购过的客户 (debnaam)。 在我的示例中,唯一的记录应该是 Brady。

我试过以下查询:

SELECT a.ordernr, a.debnaam, a.debnr, a.orddat 
FROM orkrg as a 
WHERE NOT EXISTS(SELECT b.debnr 
                 FROM orkrg as b 
                 WHERE a.ordernr = b.ordernr 
                 AND b.orddat > CONVERT(date, dateadd(year,-2,getdate())))

或使用左外连接:

SELECT * 
FROM (
      SELECT orkrg.ordernr, orkrg.debnaam, orkrg.debnr, orkrg.orddat 
      FROM orkrg 
      WHERE orkrg.orddat < CONVERT(date, dateadd(year,-2,getdate()))
     ) AS a
LEFT OUTER JOIN 
     (
      SELECT orkrg.ordernr, orkrg.debnaam, orkrg.debnr, orkrg.orddat 
      FROM orkrg 
      WHERE orkrg.orddat > CONVERT(date, dateadd(year,-2,getdate()))
     ) as b 
  ON a.ordernr = b.ordernr

但我总是得到以下结果:

ordernr debnaam    debnr    orddat
123     Coca-Cola  123      2016-01-01
1234    Brady      789      2015-03-18

有人可以帮我吗?

谢谢!

您需要使用 DATEDIFF() 过滤掉较旧的日期:

SELECT a.ordernr, a.debnaam, a.debnr, a.orddat 
FROM orkrg as a 
WHERE DATEDIFF(year, a.orddat, GETDATE()) > 2
AND A.debnr NOT IN (SELECT b.debnr FROM orkrg as b WHERE
DATEDIFF(year, b.orddat, GETDATE()) <= 2)
select a.*
from orkrg as a
where a.orddat < dateadd(year,-2,getdate()) -- this is kinda not needed
and not exists (select 1  -- NOT EXISTS is a safer option than NOT IN, where a null result can cause issues
                from orkrg as b 
                where a.debnaam = b.debnaam and 
                b.orddat > dateadd(year,-2,getdate()))

我默认使用 not exists 而不是 not in,请参阅 here 了解原因

select * 
from orders as o 
where o.debnr not in (select debnr 
                      from orders as u 
                      where orddat > CONVERT(date, dateadd(year,-2,getdate())))