【问题标题】:exclude all rows for an ID if 1 row meets condition如果 1 行满足条件,则排除 ID 的所有行
【发布时间】:2017-01-03 20:34:17
【问题描述】:

如果他们没有列出监护人,我正在尝试从联系人表中选择某些客户。

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')                      

但是我的结果只是排除了 Guardian = Y 的行,并打印 Guardian = N 的行,即使有任何与 Guardian = Y 的 ClientId 相关联的行,该 ClientId 也不应该出现在结果中.我一直在寻找如何只选择其中具有某些值的行,但是如果其中一个行匹配,我没有找到如何完全排除 ClientId 的运气。

如果有任何建议,我将不胜感激!

【问题讨论】:

  • 请向我们展示您已经提供的数据样本所需的输出。
  • @PM 77-1 期望的输出是 ClientId |联系方式 |监护人 456 | 4 | N 456 | 5 | N 456 | 6 | N
  • 请将此信息添加到您的问题中(使用Edit)。

标签: sql sql-server tsql select


【解决方案1】:

我相信您遇到这种情况的原因是您使用contactid 而不是clientid 连接子查询。我还在输出中包含了 distinct:

select distinct c.ClientId
from Contacts c
where not exists (select 1
                  from Contacts c2
                  where c2.ClientId = c.ClientId
                  and c2.Guardian = 'Y')  

【讨论】:

    【解决方案2】:

    子查询获取没有任何Guardian = 'Y'ClientIds。如果您需要完整的记录,也可以使用外部查询。如果您只需要 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
    )                
    

    【讨论】:

    • 做到了!谢谢!
    【解决方案3】:
    select * 
    from contacts 
    where ClientId not in 
    (
        select ClientId 
        from contacts 
        where Guardian = 'Y'
    )
    

    【讨论】:

      猜你喜欢
      • 2015-01-25
      • 2017-09-27
      • 2022-10-24
      • 2015-10-13
      • 2021-06-06
      • 2022-06-28
      • 1970-01-01
      • 2020-09-11
      • 1970-01-01
      相关资源
      最近更新 更多