问题描述
我想返回在sql的“全名”和“地址”列中具有重复值的行。因此,在示例中,我只希望返回前两行。我该如何编码?
解决方法
为什么返回重复值?只需合计并返回计数:
select fullname,address,count(*) as cnt
from t
group by fullname,address
having count(*) >= 2;
,
一个选项使用窗口功能:
select *
from (
select t.*,count(*) over(partition by fullname,address) cnt
from mytable t
) t
where cnt > 1
如果表具有主键,例如id
,则也可以使用exists
:
select t.*
from mytable t
where exists (
select 1
from mytable t1
where t1.fullname = t.fullname and t1.address = t.address and t1.id <> t.id
)