简体   繁体   English

有条件的 Postgres 查询

[英]Conditional Postgres Query

The PG table looks like this: 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

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.我想编写一个查询,它只列出 Name 有“A 型”记录但没有 B 型记录的行。

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 :一种方法是group by

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM