0

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

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

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

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

有什么办法可以做到这一点?

4

2 回答 2

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 )
于 2013-10-17T14:02:30.710 回答
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 的所有行,并保留所有首先出现的行。

于 2013-10-17T14:02:01.123 回答