看起来像一个简单的问题,但我很难完成它。我想要做的是返回所有具有重复ID的名称。视图看起来这样:PostgreSQL:如何选择非聚合列?
id | name | other_col
---+--------+----------
1 | James | x
2 | John | x
2 | David | x
3 | Emily | x
4 | Cameron| x
4 | Thomas | x
所以在这种情况下,我只是想要的结果:
name
-------
John
David
Cameron
Thomas
下面的查询工作,但它似乎是一个矫枉过正有两个不同的选择:
select name
from view where id = ANY(select id from view
WHERE other_col='x'
group by id
having count(id) > 1)
and other_col='x';
我相信这应该是可以做到的线下的东西:
select name from view WHERE other_col='x' group by id, name having count(id) > 1;
但是这完全没有任何回报!什么是“正确的”查询?
我只是喜欢我的第一个工作建议,还是有更好的方法?
CTE可能会很好地为你工作。 –
你只是试图避免使用多个'SELECT'语句? – Nicarus
@Ncarus是的。我想删除冗余 WHERE other_col ='x'(真实条件相当长),所以删除1'SELECT'会使其更清晰。 – nico