查找重复的条目SQL

时间:2012-06-04 17:24:05

标签: sql sql-server sql-server-2008

我有一个名为Member(唯一ID是MemberID)的表,它有许多成员重复项,只有First和Last Names不同,但是商业名称,地址,城市,州和邮政编码都是相同的。记录是重复导入的。

如何运行脚本来查找BusinessName,Addr1,City,State和ZIP都相同的重复成员。

我想在页面上列出所有内容,因此我可以选择要消除的内容。

我有什么想法可以为此创建脚本吗?

非常感谢,

2 个答案:

答案 0 :(得分:1)

您想为此使用分析函数:

select m.*
from (select m.*,
             count(*) over (partition by BusinessName, Address, City, State, ZipCode) as NumDups 
      from members m
     ) m
where NumDups > 1

NumDups告诉你有多少重复。

答案 1 :(得分:1)

select * from Member as m
where exists(select MemberID 
      from Member as m2 
      where 
           (m.BusinessName = m2.BusinessName or (m.BusinessName is null and m2.BusinessName is null)) and 
           (m.Addr1 = m2.Addr1 or (m.Addr1 is null and m2.Addr1 is null)) and 
           (m.City = m2.City or (m.City is null and m2.City is null)) and 
           (m.State = m2.State or (m.State  is null and m2.State is null)) and 
           (m.ZIP = m2.ZIP or (m.ZIP  is null and m2.ZIP is null)) and 
           m.memberID <> m2.MemberID)

使用上述查询,在哪里检查是否存在重复条目。仅当存在MemberID 匹配的副本时,子查询才会返回结果。这意味着如果有一个唯一的行,那么就没有结果,而如果有一行有一个或多个副本,那么它将被返回。