删除字段从同一个表中重复

时间:2013-10-17 13:49:29

标签: sql sql-server select duplicates sql-delete

我正在编写此查询以显示从外部源自动填充的表中的一组名称:

select MAX(UN_ID) as [ID] , MAX(UN_Name) from UnavailableNames group by (UN_Name) 

我有很多名称重复,所以我使用“分组依据”

我想在执行此选择查询后立即删除所有重复项。 (删除字段UN_Name可用两次,保留一次)

有什么办法吗?

2 个答案:

答案 0 :(得分:2)

这样的事情应该有效:

WITH CTE AS 
(
    SELECT rn = ROW_NUMBER() 
                OVER( 
                  PARTITION BY UN_Name
                  ORDER BY UN_ID ASC), * 
    FROM dbo.UnavailableNames
) 
DELETE FROM cte 
WHERE  rn > 1 

您基本上在每个组中分配一个增加的“行号”,它们共享相同的“un_name”。

然后你只删除所有“行号”大于1的行,并保留所有首先出现的行。

答案 1 :(得分:2)

With CTE As
(
Select uid,ROW_NUMBER() OVER( PARTITION BY uname order by uid) as rownum
From yourTable

)

Delete 
From yourTable
where uid in (select uid from CTE where rownum> 1 )