1

I have table with following columns in postgres.

col1    col2             col3
1       Other            a
2       Drug             b    
1       Procedure        c
3       Combination Drug d
4       Biological       e
3       Behavioral       f
3       Drug             g
5       Drug             g
6       Procedure        h

I would like to filter rows based on following filters.

select col1, col2, col3
from tbl
where col2 in ('Other', 'Drug', 'Combination Drug', 'Biological')

But this query will exclude below rows

1       Procedure        c
3       Behavioral       f

The Desired output is:

col1    col2             col3
1       Other            a
1       Procedure        c
2       Drug             b    
3       Combination Drug d
3       Behavioral       f
3       Drug             g
4       Biological       e
5       Drug             g

How can I achieve the above output without missing the mentioned rows.

Any suggestion here will be really helpful. Thanks

1
  • edited the post. so row with id = 6 should be excluded from the desired table. Commented May 12, 2020 at 8:41

1 Answer 1

1

I think you want the rows where there is as col1 containing any of the values of col2 in the list:

select col1, col2, col3
from tbl
where col1 in (
  select col1 from tbl 
  where col2 in ('Other', 'Drug', 'Combination Drug', 'Biological')
)
order by col1;

Or with EXISTS:

select t.col1, t.col2, t.col3
from tbl t
where exists (
  select 1 from tbl 
  where col1 = t.col1 
  and col2 in ('Other', 'Drug', 'Combination Drug', 'Biological')
)
order by col1;

See the demo.

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.