Row_Number() function in SQL Server 2005 - Part IIJanuary 18, 2006 In part I of this article, we saw how to generate row numbers and delete a simple single duplicate row. This article walks you through how to delete multiple duplicate rows. This article uses the new feature Row_Number() function, common table expression and the ANSI co-related subquery. Let us assume we have the following table, Mytable, in the database MyDB. Let us create the database MyDB and MyTable by using the following script. USE [MASTER] GO IF EXISTS Let us query all the rows from the table MyTable using the following Select query. SELECT * FROM MYTABLE ORDER BY ID This query displays the following results.
From the results, it is very clear that we have duplicate rows: 1, Jen, Ambelang and 25, Sandra, Mator. Step 1The first step in deleting duplicate rows is to generate a unique row id for the entire table. This can be done using the Row_Number() function. Let us generate the unique numbers by executing the following query: SELECT ROW_NUMBER() OVER (ORDER BY ID) AS ROW, ID,LNAME,FNAME FROM MYTABLE This query produces the following results.
Step 2The second step in deleting duplicate rows is to generate unique row ids for every group. Now, by using a co-related sub-query we can produce unique row ids for each group. SELECT ROW,GROUPROW= CASE WHEN ID=ID THEN (SELECT COUNT(*) FROM (SELECT ROW_NUMBER() OVER (ORDER BY ID) AS ROW, ID,LNAME,FNAME FROM MYTABLE ) AS A WHERE A.ID=B.ID AND A.ROW<B.ROW)+1 END,ID,FNAME,LNAME FROM (SELECT ROW_NUMBER() OVER (ORDER BY ID) AS ROW, ID,LNAME,FNAME FROM MYTABLE )AS B This query would produce the following results with a unique id for each group.
Step 3The last step in deleting duplicate rows is to use the common table expression, as shown below. WITH DUPLICATE(ROW,GROUPROW,ID,FNAME,LNAME) AS ( SELECT ROW,GROUPROW= CASE WHEN ID=ID THEN (SELECT COUNT(*) FROM (SELECT ROW_NUMBER() OVER (ORDER BY ID) AS ROW, ID,LNAME,FNAME FROM MYTABLE ) AS A WHERE A.ID=B.ID AND A.ROW<B.ROW)+1 END,ID,FNAME,LNAME FROM (SELECT ROW_NUMBER() OVER (ORDER BY ID) AS ROW, ID,LNAME,FNAME FROM MYTABLE )AS B ) DELETE FROM DUPLICATE WHERE GROUPROW<>1 Let us query all the rows from the source table, Mytable, by using the following Select Query. SELECT * FROM MYTABLE ORDER BY ID This query displays the following results:
From the results, it is clear that duplicates from the table, Mytable, have been removed. ConclusionThe main intent of this article was to demonstrate the use of SQL Server 2005s new feature Row_number() function and Common Table Expression, with the help of co-related sub-query, to delete duplicate rows. |