简体   繁体   English

根据另一列中的值选择一个ID存在多个行的不同记录

[英]select distinct records where multiple rows exist for one ID based on values in another column

So I'm not exactly sure if my title is correct or misleading. 因此,我不确定我的标题是正确的还是误导性的。 It sounds simple, but I can't figure it out and haven't found a good example. 听起来很简单,但我无法弄清楚,也找不到很好的例子。

I want to select the distinct ID's from a table where the ID does not match to a certain code. 我想从ID不匹配特定代码的表中选择唯一ID。 For instance I have tableA as below: 例如我有tableA如下:

tableA 表A

ID          Code 
====        ==== 
1            AAA 
1            BBB 
1            CCC 
2            AAA 
2            DDD 
2            EEE 
3            BBB 
3            GGG 
3            HHH

The only result I would like to return is ID 3 since ID 1 and ID 2 match to code 'AAA'. 我要返回的唯一结果是ID 3,因为ID 1和ID 2匹配代码“ AAA”。

I've tried: 我试过了:

SELECT disctinct(ID) from tableA where code <> 'AAA' 

but this returns ID 1, 2, and 3. I'm not sure if a group by would work either because I don't even want ID 1 and 2 to be returned. 但这会返回ID 1、2和3。我不确定group by是否会起作用,因为我什至都不希望返回ID 1和2。

Try using NOT IN : 尝试使用NOT IN

SELECT ID
FROM TableA
WHERE ID NOT IN(SELECT ID
            FROM TableA
            WHERE CODE='AAA')

IN determines whether a specified value matches any value in a subquery or a list. IN确定指定的值是否与子查询或列表中的任何值匹配。 Read more here . 在这里阅读更多。

Explanation: 说明:

Inner query selects all IDs which as CODE=AAA . 内部查询会选择所有ID为CODE=AAA ID。 The outer query will select all IDs which are not in the result return by inner query. 外部查询将选择内部查询未返回的所有ID。

ie, With the given data, inner query will return (1,2). 即,使用给定的数据,内部查询将返回(1,2)。 Outer query will select ID which are not in (1,2) which is ofcourse 3. 外部查询将选择不在(1,2)中的ID,这当然是3。

This returns all rows for a given id: 这将返回给定ID的所有行:

select *
from tab as t1
where not exists
  (select * from tab as t2
   where t1.id = t2.id
   and code = 'AAA')

And this just the ids without 'AAA': 而这只是不含“ AAA”的ID:

select id
from tab
group by id
having count(case when code = 'AAA' then 1 end) = 0

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM