我有 2 个表(AllClients 和 AllActivities),需要检索以下信息:
我需要一份没有相关活动的客户列表。
这是我的表格,其中包含一些虚假数据,以帮助解释我在寻找什么:
我基本上需要 sql 来检索 Sam Johnson,因为他没有任何活动,而且他的 TypeCode 为“P”。
您不一定需要加入
select *
from AllClients c
where TypeCode = 'P'
and not exists (select 1 from AllActivities a where a.LookupCode = c.LookupCode)
select c.*
from AllClients c
left join AllActivities a on a.LoopupCode = c.LoopupCode
where a.LoopupCode is null
and c.TypeCode = 'P'
SELECT *
FROM
AllClients
WHERE
NOT EXISTS(SELECT 1 FROM AllActivities WHERE AllActivities.lookUpCode = AllClients.lookUpCode)
AND TypeCode = 'P'
由于IN
缺少版本:
select *
from AllClients c
where TypeCode = 'P'
and LookupCode not in (select distinct LookupCode from AllActivities)