删除表中具有相同值的重复行但在SQL Server中保留一行

时间:2016-11-11 18:27:08

标签: sql sql-server stored-procedures sql-server-2012

这是我的存储过程中的查询之一,我将Main表中的记录插入到重复表中,之后我想删除主表中的重复行。

这是我的代码

 IF EXISTS (SELECT * 
            FROM [JOB] 
            WHERE 
              AND ExternalSourceId = @ExternalSourceId 
              AND Id <> @Id 
              AND IsActive = 1)
 BEGIN
    INSERT INTO DupJob 
        SELECT * 
        FROM [JOB] j 
        WHERE 
          AND ExternalSourceId = @ExternalSourceId 
          AND Id <> @Id 
          AND IsActive = 1 
          AND NOT EXISTS (SELECT * FROM DupJob dj WHERE J.Id = dj.Id)     
    -- the delete should delete all duplicates except one ?
 END    

寻求帮助继续,谢谢

1 个答案:

答案 0 :(得分:1)

row_number()和CTE是一种方便的方法。我不确定你想要的逻辑是什么,但它是这样的:

with todelete as (
      select j.*,
             row_number() over (partition by OrganizationName, JobTitle, PostalCode, ExternalSourceId)
                                order by id) as seqnum
      from job j
     )
delete from todelete
    where seqnum > 1;

这会在partition by的每列中保留一行,最小值为id