【问题标题】:Conditional Postgres Query条件 Postgres 查询
【发布时间】:2020-02-19 19:36:35
【问题描述】:

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

【问题讨论】:

    标签: sql database postgresql nested-select


    【解决方案1】:

    您可以使用嵌套选择:

    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'
    

    【讨论】:

      【解决方案2】:

      一种方法是group by:

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

      【讨论】:

        猜你喜欢
        • 2016-06-08
        • 1970-01-01
        • 1970-01-01
        • 2012-05-01
        • 2020-05-09
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-02-21
        相关资源
        最近更新 更多