【问题标题】:SQL Return only duplicate recordsSQL 只返回重复记录
【发布时间】:2020-11-03 14:46:17
【问题描述】:

我想返回在 SQL 的全名和地址列中具有重复值的行。所以在这个例子中,我只想返回前两行。如何编码?

【问题讨论】:

  • (1) 用您正在使用的数据库标记您的问题。 (2) 你的表有主键吗?
  • 请用您正在运行的数据库标记您的问题:mysql、oracle、sqlserver...?

标签: sql count subquery sql-server-2017


【解决方案1】:

为什么要返回重复值?只需汇总并返回计数:

select fullname, address, count(*) as cnt
from t
group by fullname, address
having count(*) >= 2;

【讨论】:

  • 我想我真的不想聚合它。即使全名和地址相同,表中的其他变量也会有所不同。我不知道如何解决这个问题
  • @hauger2 。 . .这为您提出的问题提供了答案。 GMB 的答案就是你想要的答案。
【解决方案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
)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-01-26
    • 1970-01-01
    相关资源
    最近更新 更多