查询列值的多行的SQL查询

问题描述 投票:0回答:3

我正在尝试创建一个查询,根据列中的重复值选择行

Row 1:             Row 2:            Row 3:           Row 4:
Record_Key = 1     Record_Key = 1    Record_Key = 2   Record_Key = 3
Type = 'AED'       Type = 'ACD'      Type = 'AED'     Type = 'AED'

我只想选择具有Record_KeyAED的行,这些行没有与ACD相关联的Record_Key

所以在我提供的例子中,我只想选择Row 3Row 4

我不能说:

Select * From Table Where Type != 'ACD'

因为当我只想要Row 1Row 3时,这会返回Row 4Row 3Row 4。我无法围绕构造此查询,或SQL和我提供的表不允许这种选择吗?

sql sql-server
3个回答
0
投票

使用不存在

    select t1.* from tab t1
    where not exists ( select 1 from tab t2 where t1.Record_Key=t2.Record_Key
                                       and type='ACD')

产量

Record_Key  Type
2           AED
3          AED

demo


0
投票

你可以使用not exists

select t.*
from table t
where t.type = 'AED' and 
      not exists (select 1 from table t1 where t1.record_key = t.record_key and t1.type = 'ACD');

0
投票

你可以group by record_key并只保留record_keys唯一现有的type'AED'

select record_key, max(type) type 
from tab
where type in ('AED', 'ACD') 
group by record_key
having min(type) = 'AED' and max(type) = 'AED'
© www.soinside.com 2019 - 2024. All rights reserved.