我正在尝试创建一个查询,根据列中的重复值选择行
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_Key
的AED
的行,这些行没有与ACD
相关联的Record_Key
。
所以在我提供的例子中,我只想选择Row 3
和Row 4
。
我不能说:
Select * From Table Where Type != 'ACD'
因为当我只想要Row 1
和Row 3
时,这会返回Row 4
,Row 3
和Row 4
。我无法围绕构造此查询,或SQL和我提供的表不允许这种选择吗?
使用不存在
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
你可以使用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');
你可以group by record_key
并只保留record_key
s唯一现有的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'