Remove duplicate records except the first record i

2019-03-06 04:43发布

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".

3条回答
Root(大扎)
2楼-- · 2019-03-06 04:59

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.

查看更多
放我归山
3楼-- · 2019-03-06 05:00

Seems like a simple distinct modifier would do the trick:

SELECT DISTINCT name
FROM   mytable
查看更多
霸刀☆藐视天下
4楼-- · 2019-03-06 05:00

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
查看更多
登录 后发表回答