【发布时间】:2016-11-19 04:02:18
【问题描述】:
似乎是一个简单的问题,但我无法完成它。我想要做的是返回所有具有重复 ID 的名称。视图如下所示:
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 是的。我想删除多余的 WHERE other_col='x' (实际情况很长)所以删除 1
SELECT会更清楚。
标签: sql postgresql aggregate having