我试图从联系人表中选择某些客户,如果他们没有列出监护人的话。
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因此,我的目标是客户端456将显示在我的查询结果中,但不是客户端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') 但我的结果只是排除了卫报=Y的行,并打印了卫报= N的行,即使有任何与ClientId相关的行,其中卫报= Y,ClientId也不应该出现在结果中。我一直在查找如何只选择其中包含某些值的行,但如果ClientId中的某一行匹配,我将无法找到完全排除它的方法。
如有任何建议,我将不胜感激!
发布于 2017-01-03 20:37:30
子查询获取没有任何ClientId的Guardian = 'Y'。如果您需要完整的记录,也可以使用外部查询。如果您只需要ID,那么只使用子查询
select *
from Contacts
where ClientId in
(
select ClientId
from Contacts
group by ClientId
having sum(case when Guardian = 'Y' then 1 else 0 end) = 0
) 发布于 2017-01-03 20:39:27
我认为您之所以会遇到这种情况,是因为您使用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') 发布于 2017-01-07 16:31:25
select *
from contacts
where ClientId not in
(
select ClientId
from contacts
where Guardian = 'Y'
)https://stackoverflow.com/questions/41451891
复制相似问题