我在此停留了一段时间。想象一下我有这张桌子:
diagId | astigmatic
1 | No
1 | Yes
2 | No
3 | No
4 | No
5 | No
5 | Yes
6 | No
而且我想要输出:
diagId | astigmatic
1 | Yes
2 | No
3 | No
4 | No
5 | Yes
6 | No
因此,如果有一个带有yes和no的diagId,我希望Yes元组遍历,而No元组消失。
我该如何实现?谢谢!
一种方法是聚合:
select diagid, max(astigmatic) as astigmatic
from t
group by diagid;
这是有效的,因为[C0
'yes'
。或者,在概念上类似的方法,但在Postgres中可能更快:
'no'
另一种方法是
select distinct on (diagid) t.* from t order by diagid, astigmatic desc;
和or
:
not exists
前两个方法每
select t.* from t where t.astigmatic = 'yes' or (t.astigmatic = 'no' and not exists (select 1 from t t2 where t2.id = t.id and t2.astigmatic = 'yes' ) );
返回一行-保证。如果给定的id
有多个'yes'
或'no'
,则最后一个方法可以返回多行。