PG表如下所示:
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有"类型a"记录而没有类型B记录的行。
这就是我所希望的结果:
5 - Name 3 - Type A
您可以使用嵌套选择:
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';