合并表MSSQL上的重复联系人

时间:2014-04-08 17:57:25

标签: sql sql-server

我需要合并并删除表格上的重复联系人。

第1部分:由于某些副本具有值(电话,传真等),而其他副本没有,我使用MAX函数来获取所有相应的值。很少有相互矛盾的信息。这个矛盾的信息将手动修复。我已使用MAX函数将数据存储到临时表并更新了联系表,以便所有重复的联系人都具有相同的信息。 第2部分:现在我需要选择1个重复的联系人作为主服务器并将其他“子”重复联系人的引用更新为主服务器,然后删除子重复的联系人。

我试图从第2部分开始,但我不确定如何从复制中选择一个不同的联系人ID。使用merge语句(第1部分和第2部分组合)也可以轻松实现。

select DISTINCT c.namefml from contact c
where c.contactrecordtype = 'CONTACT'
and c.inactive<>'T'

group by c.namefml
HAVING COUNT (c.namefml)>1

This selects the distinct duplicate contacts based on the name. Now how would I select TOP 1 from each of these: 


 Select DISTINCT contactid, namefml
    from contact c
    where namefml = (select DISTINCT c.namefml from contact c
    where c.contactrecordtype = 'CONTACT'
    and c.inactive<>'T'

    group by c.namefml
    HAVING COUNT (c.namefml)>1) 

这不起作用。

Select DISTINCT contactid, c.namefml
from contact c
inner join (select DISTINCT c.namefml from contact c
where c.contactrecordtype = 'CONTACT'
and c.inactive<>'T'

group by c.namefml
HAVING COUNT (c.namefml)>1) s 
on s.namefml=c.namefml

这也不起作用,因为它获得了所有重复项而不仅仅是前1项。

1 个答案:

答案 0 :(得分:0)

如果在您的select语句中使用row_number() OVER(Partition by namefml order by namefml) as [RowNum]。这将为您提供一个名为RowNum的列,该列对于每个相同的namefml递增1。

    SELECT DISTINCT contactid,
                    namfml,
                    ROW_NUMBER() OVER(PARTITION BY namefml ORDER BY contactid) AS [RowNum]
    FROM contact c
    WHERE RowNum = 1

所以这将选择重复的所有第一。

希望这是你正在寻找的东西!

相关问题