Single Query to delete and display duplicate records

前端 未结 3 960
感情败类
感情败类 2021-02-10 04:35

One of the question asked in an interview was,

One table has 100 records. 50 of them are duplicates. Is it possible with a single query to delete the

3条回答
  •  逝去的感伤
    2021-02-10 04:51

    Lieven's Answer is a good explanation of how to output the deleted rows. I'd like to add two things:

    1. If you want to do something more with the output other than displaying it, you can specify OUTPUT INTO @Tbl (where @Tbl is a table-var you declare before the deleted);

    2. Using MAX, MIN, or any of the other aggregates can only handle one duplicate row per group. If it's possible for you to have many duplicates, the following SQL Server 2005+ code will help do that:

     

    ;WITH Duplicates AS
    (
        SELECT
            ID,
            ROW_NUMBER() OVER (PARTITION BY DupeColumn ORDER BY ID) AS RowNum
    )
    DELETE FROM MyTable
    OUTPUT deleted.*
    WHERE ID IN
    (
        SELECT ID
        FROM Duplicates
        WHERE RowNum > 1
    )
    

提交回复
热议问题