MSSQL sql server 2005/2008 row_number() function application – delete duplicate records in the table and keep only one unique data

Original: MSSQL sql server 2005/2008 row_number() function application - delete duplicate records in the table, only keep a non-duplicate data

Reprinted from: http://www.maomao365.com/?p=4942

The following mainly describes: the method of obtaining only one duplicate data

The function of the row_number function in the database is to generate a number for each row according to certain rules.
We often use this attribute to perform paging operations on the table. Below we will describe the use of the row_number function to delete duplicate data rows in the table.

/* Create table */ 
create  table A(keyId int ,info varchar ( 20 ))
 go  
/* Generate data */ 
insert  into A(keyId,info) values 
​​( 1 , ' a ' ),( 2 , ' b ' ) ,( 3 , ' C ' ),( 4 , ' d ' ),( 5 , ' e ' ),
(1,'a'),(21,'b1'),(31,'C1'),(4,'d'),(51,'e'),
(1,'a'),(6,'b1'),(7,'C1'),(4,'d000'),(10,'e')
go


/* Delete the other items in the keyId duplicate data */ 
delete  [ A2 ]  from  
( select row_number() over (Partition By keyId order  by keyId) as keyId2, *  from A ) as  [ A2 ] 
where  [ A2 ] .keyId2   > 1 
 

/* 
/*Delete all the other columns in the duplicate data */ 
delete  [ A2 ]  from  
( select row_number() over (Partition By keyId,info order  by keyId) as keyId2, *  from A ) as  [ A2 ] 
where  [ A2 ] .keyId2   > 1  
 */

/* Display the deleted data */

select * from A 
go

truncate table A 
drop table A 
go

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325227105&siteId=291194637