PostgreSQL中是否有一种方法来获取id为status ='A'或NULL的ID号?
说我有一张桌子
+-------------+
| ID | STATUS |
+-------------+
| 1 | 'A' |
| 1 | null |
| 2 | 'A' |
| 3 | 'A' |
| 3 | 'C' |
+-------------+
我想要一张桌子
+----+
| ID |
+----+
| 1 |
| 2 |
+----+
距离我开始为此奋斗已有几个小时了。
答案 0 :(得分:4)
您可以使用4096
和group by
:
having
或者作为select id
from the_table
group by id
having sum( status not in ('A', 'B')::int ) = 0;
:
not exists
答案 1 :(得分:0)
这应该有效:
select distinct id
from table_name
where status = 'A'
or status = 'B'
答案 2 :(得分:0)
使用distinct
和sub-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')
)
答案 3 :(得分:0)
您可以使用这样的查询(适用于多种品牌的数据库):
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;
答案 4 :(得分:0)
Gordon Linoff建议按ID汇总,BarbarosÖzhan也这样做。我也喜欢这种方法。无论如何,对于PostgreSQL,我都会使用EVERY
来提高可读性:
select id
from mytable
group by id
having every(status = 'A' or status is null);