删除 SQL 中除第一条记录外的重复记录

2022-01-10 00:00:00 sql duplicates select tsql sql-server

我想删除除第一个之外的所有重复记录.

I want to remove all duplicate records except the first one.

喜欢:

NAME
R
R
rajesh
YOGESH
YOGESH

现在我想删除上面的第二个R"和第二个YOGESH".

Now in the above I want to remove the second "R" and the second "YOGESH".

我只有一列名称为NAME".

I have only one column whose name is "NAME".

推荐答案

使用 CTE(我有几个在生产中).

Use a CTE (I have several of these in production).

;WITH duplicateRemoval as (
    SELECT 
        [name]
        ,ROW_NUMBER() OVER(PARTITION BY [name] ORDER BY [name]) ranked
    from #myTable
    ORDER BY name
)
DELETE
FROM duplicateRemoval
WHERE ranked > 1;

说明:CTE 将获取您的所有记录并为每个唯一条目应用一个行号.每个额外的条目将获得一个递增的数字.将 DELETE 替换为 SELECT * 以查看它的作用.

Explanation: The CTE will grab all of your records and apply a row number for each unique entry. Each additional entry will get an incrementing number. Replace the DELETE with a SELECT * in order to see what it does.

相关文章