我仅需要基于其他列属性名称合并两行

问题描述 投票:1回答:1

我在此停留了一段时间。想象一下我有这张桌子:

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元组消失。

我该如何实现?谢谢!

sql postgresql view
1个回答
1
投票

一种方法是聚合:

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',则最后一个方法可以返回多行。

© www.soinside.com 2019 - 2024. All rights reserved.