SQL查询在多行中查找列值

时间:2019-03-14 19:03:35

标签: sql sql-server

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

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_KeyAEDACD没有关联的行。

因此,在我提供的示例中,我只想选择Record_KeyRow 3

我不能说:

Row 4

因为当我只想要Select * From Table Where Type != 'ACD' Row 1时,这将返回Row 3Row 4Row 3。我不能全神贯注于构造此查询,还是SQL和提供的表不允许这种选择?

3 个答案:

答案 0 :(得分: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');

答案 1 :(得分: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

答案 2 :(得分:0)

您可以group by record_key并仅保留record_key的地方,其中仅有的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'