我正在尝试从联系人表中选择某些客户(如果他们没有列出监护人)。
ClientId | ContactId | Guardian
123 | 1 | Y
123 | 2 | N
123 | 3 | N
456 | 4 | N
456 | 5 | N
456 | 6 | N
期望的输出:
ClientId | ContactId | Guardian
456 | 4 | N
456 | 5 | N
456 | 6 | N
所以我的目标是 Client 456 将出现在我的查询结果中,但是not客户123.我写了以下内容:
select * from Contacts
where Guardian <> (case when Guardian = 'Y'
then Guardian
else ''
end)
我也尝试过
select * from Contacts c
where not exists (select 1
from Contacts c2
where c2.ContactId = c.ContactId
and c.Guardian = 'Y')
但我的结果只是排除 Guardian = Y 的行,并打印 Guardian = N 的行,即使有任何行与 Guardian = Y 的 ClientId 关联,该 ClientId 不应显示在结果中。我一直在寻找如何仅选择其中包含某些值的行,但我没有找到如何在其中一行匹配时完全排除 ClientId 的方法。
如果有任何建议,我将非常感激!
我相信您遇到这种情况的原因是因为您使用连接子查询contactid
代替clientid
。我还在输出中包含了不同的内容:
select distinct c.ClientId
from Contacts c
where not exists (select 1
from Contacts c2
where c2.ClientId = c.ClientId
and c2.Guardian = 'Y')
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)