SQL SERVER按多字段查找重复的数据并删除只保留一条

由于一次操作失误,给表中插入了多条重复的数据,所以就需要删除重复的数据只保留一条,一时想不到好方法,各种查资料,终于找到了,特意写到这里,方便以后自己用~

查询:

select A.n_PatentID,A.s_OtherFileName,A.s_FileName FROM TB_OtherFiles A,
(SELECT n_PatentID,s_OtherFileName,s_FileName FROM TB_OtherFiles
GROUP BY n_PatentID,s_OtherFileName,s_FileName HAVING COUNT(1)>=2
) AS B

WHERE A.s_OtherFileName=B.s_OtherFileName AND A.n_PatentID=B.n_PatentID AND A.s_FileName=B.s_FileName AND A.n_PatentID >0
order by n_PatentID

 

删除:

DELETE T FROM (SELECT n_PatentID,s_OtherFileName,s_FileName,s_recycle, ROW_NUMBER()OVER(PARTITION BY n_PatentID,s_OtherFileName,s_FileName ORDER BY RAND()) AS RN FROM TB_OtherFiles where n_PatentID>0) AS t WHERE RN>1 

 

posted @ 2017-04-07 12:07  yixuan.han  阅读(2946)  评论(0编辑  收藏  举报