我正在尝试
select columns Age, Height, House_number, Street
from my_table
where count(combination of House_number, Street)
occurs more than once.
我的表格看起来像这样
Age, Height, House_number, Street
15 178 6 Mc Gill Crst
85 166 6 Mc Gill Crst
85 166 195 Mc Gill Crst
18 151 99 Moon Street
52 189 14a Grimm Lane
我希望的结果看起来像这样
Age, Height, House_number, Street
15 178 6 Mc Gill Crst
85 166 6 Mc Gill Crst
粘住!
答案 0 :(得分:6)
最好的方法是使用窗口函数,假设您的数据库支持它们:
select columns Age, Height, House_number, Street
from (select t.*, count(*) over (partition by house_number, street) as cnt
from my_table t
) t
where cnt > 1
这是在Oracle中使用Windows功能(也称为分析功能)。表达式count(*) over (partition by house_number, street)
计算每个house_number和街道组合的行数。这有点像做group by
,但它会将计数添加到每一行,而不是将多行合并为一行。
完成后,只需选择值大于1的行即可。
答案 1 :(得分:2)
由于您没有提到您正在使用的RDBMS,因此下面的查询将在大多数RDBMS上工作。
SELECT *
FROM tableName
WHERE (House_number, Street) IN
(
SELECT House_number, STREET
FROM tableName
GROUP BY House_number, STREET
HAVING COUNT(*) >= 2
)
答案 2 :(得分:0)
听起来你需要一个NOT DISTINCT。以下内容可能会为您提供所需内容:Multiple NOT distinct
答案 3 :(得分:0)
如果您没有窗口函数,则可以使用带有JOIN
的子查询。子查询获取计数大于1的house_number
和street
列表,然后将此结果用于连接回您的表:
select t1.age,
t1.height,
t1.house_number,
t1.street
from my_table t1
inner join
(
select house_number, street
from my_table
group by house_number, street
having count(*) > 1
) t2
on t1.house_number = t2.house_number
and t1.street = t2.street