Skip to content
Advertisement

How can i query to get to this result?

id     string     id2  
1        a         1
2        b         1
3        a         2
4        c         2
5        d         3

Ok, so i can get SELECT * FROM table WHERE string NOT IN ('a','c'):

2        b         1
5        d         3 

but i also want to not get the rest of the rows that contain a or c with the same id2. result:

5        d         3

Advertisement

Answer

You can use not exists:

select t.*
from t
where not exists (select 1
                  from t t2
                  where t2.id2 = t.id2 and t2.string in ('A', 'C')
                 );

If you just want the id2 values, you might find aggregation convenient:

select id2
from t
group by id2
having sum(case when string in ('A', 'C') then 1 else 0 end) = 0;
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement