Remove duplicate records except the first record in SQL

后端 未结 3 2023
情话喂你
情话喂你 2020-12-22 05:36

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

相关标签:
3条回答
  • 2020-12-22 05:51

    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
    
    0 讨论(0)
  • 2020-12-22 05:56

    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.

    0 讨论(0)
  • 2020-12-22 06:00

    Seems like a simple distinct modifier would do the trick:

    SELECT DISTINCT name
    FROM   mytable
    
    0 讨论(0)
提交回复
热议问题