简体   繁体   中英

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. For instance I have tableA as below:

tableA

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

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.

Try using 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. Read more here .

Explanation:

Inner query selects all IDs which as CODE=AAA . The outer query will select all IDs which are not in the result return by inner query.

ie, With the given data, inner query will return (1,2). Outer query will select ID which are not in (1,2) which is ofcourse 3.

This returns all rows for a given 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':

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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