简体   繁体   中英

Conditional Postgres Query

The PG table looks like this:

id - name   - type
1  - Name 1 - Type A
2  - Name 1 - Type B
3  - Name 2 - Type A
4  - Name 2 - Type B
5  - Name 3 - Type A

I would like to write a query that only lists rows in which Name has a 'Type A' record but not a Type B record.

This is the result I am hoping for:

5  - Name 3 - Type A

You can use a nested select:

select t.*
from table_name t
where not exists(
    select 1
    from table_name it
    where t.name = it.name
    and it.type = 'Type B'
)
and t.type = 'Type A'

One method is group by :

select name
from t
group by t
having min(type) = max(type) and min(type) = 'Type A';

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