1
Group_No Id Status
1 101 Active
1 102 Active
2 201 Active
2 202 Approved
2 203 Active
3 301 Inactive
3 302 Active
4 401 Denied
4 402 Denied

I have to select the groups which all Ids have either 'Active' OR 'Approved' value in Status column. I tried below query.

select group_no
from <table>
where status in ('Active','Approved') 
group by group_no 
having(count(distinct status)) = 1;

The desired output should be groups 1 and 2. But I am facing problem since 'Active' and 'Approved' are distinct but they are to be considered as same for my purpose. Please suggest how to achieve desired output.

4
  • Please explain more precise your intention. If you want to only accept "Active" and "Approved", why not write something like SELECT ...FROM...WHERE status IN ('Active','Approved') AND group_no NOT IN (SELECT group_no FROM...WHERE status IN ('Inactive','Denied')) ? Commented Oct 25, 2022 at 7:45
  • Remove the WHERE clause, and use HAVING clause to make sure there are no other status values. Commented Oct 25, 2022 at 7:51
  • @JonasMetzler There are several other statuses apart from 'Inactive' or 'Denied', so its difficult to put then all inside "IN" in the subquery. Commented Oct 25, 2022 at 7:57
  • Ok, you can of course also write ...NOT IN ('Active','Approved') instead. Commented Oct 25, 2022 at 7:58

1 Answer 1

3

If you want to avoid sub-selects and want to be flexible in terms of new status to be introduced, you could do something like this:

SELECT group_no
FROM <table>
GROUP BY group_no
HAVING 1 = MIN(CASE WHEN status IN ('Active', 'Approved') THEN 1 ELSE 0 END)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.