Remove duplicate records except the first record in SQL

微笑、不失礼 提交于 2019-12-20 07:11:54

问题


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

Like :

NAME
R
R
rajesh
YOGESH
YOGESH

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

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


回答1:


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;

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.




回答2:


Seems like a simple distinct modifier would do the trick:

SELECT DISTINCT name
FROM   mytable



回答3:


This is bigger code but it works perfectly where you don't take the original row but find all the duplicate Rows

    select majorTable.RowID,majorTable.Name,majorTable.Value from 
    (select outerTable.Name, outerTable.Value, RowID, ROW_NUMBER() 
over(partition by outerTable.Name,outerTable.Value order by RowID)
     as RowNo from @Your_Table outerTable inner join
    (select Name, Value,COUNT(*) as duplicateRows  FROM @Your_Table group by Name, Value 
having COUNT(*)>1)innerTable on innerTable.Name = outerTable.Name 
    and innerTable.Value = outerTable.Value)majorTable where MajorTable.ROwNo <>1


来源:https://stackoverflow.com/questions/46117659/remove-duplicate-records-except-the-first-record-in-sql

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!