我有一个帐户和一个联系人表格,我正在尝试查找与该帐户关联的任何联系人都没有特定字段值的任何帐户。
场景1:账户WaffleHouse有3个联系人,其中1个联系人在字段中有值" Field1"。此帐户不会在结果集中返回。
场景2:账户PancakeHouse有5个联系人,联系人中没有人在该字段中有值" Field1"设为TRUE。此帐户在结果集中返回。
我尝试了这段代码,它返回的任何帐户都有一个联系人,其中字段为空或为空。
select distinct a.accountid
from account as a
inner join contact as c
on a.accountid = c.accountid
where (c.Field1 is null or c.Field1 = '')
答案 0 :(得分:2)
试试这个:
SELECT *
FROM Accounts a
WHERE NOT EXISTS ( SELECT *
FROM contact c
WHERE a.accountid = c.accountid
AND c.Field1 = 'TRUE' )
或者:
SELECT *
FROM Accounts a
WHERE NOT EXISTS ( SELECT *
FROM contact c
WHERE a.accountid = c.accountid
AND c.Field1 <> '' )
答案 1 :(得分:1)
你非常接近 - 只需使用一些聚合(GROUP BY
)和MAX
函数来获得你想要的东西,如下所示:
select a.accountid
from account as a
inner join contact as c
on a.accountid = c.accountid
group by a.accountid
having MAX(isnull(c.Field1, '')) = ''
答案 2 :(得分:1)
select distinct a.accountid
from account
except
select c.accountid
from contact c
where c.Field1 is not null