2012-06-04 129 views
3

我有一个叫做Member(唯一ID是MemberID)的表,它有许多成员重复,只有第一个和最后一个名字不同,但商业名称,地址,城市,州和邮政编码都是一样。记录导入重复。查找重复的条目SQL

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

我想列在一个页面上,所以我可以选择哪些消除。

任何想法如何为此创建脚本?

提前许多感谢,

保罗

回答

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) 

通过上述查询,where检查是否存在重复条目。子查询返回的结果仅在存在MemberID确实不是匹配的副本时发生。这意味着如果有一个独特的行,那么将不会有结果,而如果有一行有一个或多个副本,那么它将被返回。

+0

完美的作品..非常感谢..! – neojakey

+0

只是为了完整性:这不会给你任何地址列中包含NULL的重复项。 –

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告诉你有多少重复的也有。