条件 Postgres 查询

Conditional Postgres Query

PG table 看起来像这样:

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

我想编写一个查询,只列出 Name 有 'Type A' 记录但没有类型 B 记录的行。

这是我希望的结果:

5  - Name 3 - Type A

您可以使用嵌套 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'

一种方法是group by:

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