我试过多次查询,但他们没有工作。这也可能是很简单的。
下面是一个示例表:
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)。在我的例子中唯一的记录应该是布雷迪。
我已经试过以下查询:
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())))
或用LEFT OUTER JOIN:
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
可能有人请帮助我吗?
谢谢!
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为什么
您需要使用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 *
from orders as o
where o.debnr not in (select debnr
from orders as u
where orddat > CONVERT(date, dateadd(year,-2,getdate())))