PostgreSQL - 如果所有列值都是 'A' 或 NULL,我如何 return ids

PostgreSQL - How can I return ids if all column values are 'A' or NULL

在 PostgreSQL 中有没有办法获取 status='A' 或 NULL 的 ID 号?

说我有一个 table

+-------------+
| ID | STATUS |
+-------------+
| 1  |  'A'   |
| 1  |  null  |
| 2  |  'A'   |
| 3  |  'A'   |
| 3  |  'C'   |
+-------------+

我想得到一个 table

+----+
| ID | 
+----+
| 1  |
| 2  | 
+----+

自从我开始为此苦苦挣扎已经有好几个小时了。

这应该有效:

select distinct id
from table_name
where status = 'A'
or status = 'B'

使用 distinctsub-query 随着您的示例更改,现在查询将是

select distinct id from the_table where id not in(
select distinct id from the_table where status not in('A') and status is not null
  )

http://sqlfiddle.com/#!17/10edf/3

根据之前的样本

select distinct id from the_table where id not in(
    select distinct id from the_table where status not in('A','B')
      )

http://sqlfiddle.com/#!17/2318d/10

您可以使用 group byhaving:

select id
from the_table
group by id 
having sum( status not in ('A', 'B')::int ) = 0;

或者,如 not exists:

select distinct t.id
from the_table t
where not exists (select 1 from the_table t2 where t2.id = t.id and t2.status not in ('A', 'B'));

您可以使用这样的查询(适用于多个品牌的数据库):

select ID
  from tab
 group by ID
 having sum(case when Status != 'A' and Status != 'B' then 1 else 0 end )=0;

根据您上次的编辑,只需将 Status!='B' 替换为 Status !=''(或 Status is not null):

select ID
  from tab
 group by ID
 having sum(case when Status != 'A' and Status != '' then 1 else 0 end )=0;

SQL Fiddle Demo

Gordon Linoff 建议按 ID 聚合,Barbaros Özhan 也这样做了。这也是我喜欢的方法。无论如何,对于 PostgreSQL,我会使用 EVERY 来提高可读性:

select id
from mytable
group by id
having every(status = 'A' or status is null);