Reputation: 3
I have a table with a list of IDs that I need to exclude rows from. For each row, an ID can have one value in the comment_code column. I need to exclude IDs from my results that have a combination of two specific values and keep IDs that have only one of those two values. Sorry if this isn't clear.
Table example:
ID SEQUENCE FUNCTION COMMENT_CODE
---------------------------------------------------------------
1 1 tree apple
1 2 bush orange
2 1 tree apple
2 2 tree banana
3 1 bush strawberry
Output needed:
ID SEQUENCE FUNCTION COMMENT_CODE
---------------------------------------------------------------
2 1 tree apple
Basically, if an ID has a row with 'apple' as the comment_code and a row with 'orange' as the comment code, I don't want to see that ID in my results. If an ID has a row with 'apple' as a comment code, I want to see them in my results regardless of any other comment_code they may have as long as they don't have the orange comment code.
Any help would be greatly appreciated. I've tried using a combination of exists and not exists clauses as well as listagg to group the comment_code values together for each ID, but I'm not getting the expected result.
Upvotes: 0
Views: 6383
Reputation: 1
select *
from table t
where exists (select 1 from dual
where t.function = 'tree'
and t.comment_code = 'apple')
Upvotes: -1
Reputation: 1269683
This approach uses aggregation to find all id
s that have both values. This is used as an exclusion list using a left outer join
:
select *
from table t left outer join
(select id
from table t
group by t.id
having sum(case when comment = 'apple' then 1 else 0 end) > 0 and
sum(case when comment = 'orange' then 1 else 0 end) > 0
) toexclude
on t.id = toexclude.id
where toexclude.id is null;
Upvotes: 2
Reputation: 20804
Something like this should work.
select *
from yourtable
where sequence = 1
and whatever
Upvotes: 0