MSSQL sql server 2005/2008 row_number()函數應用之–刪除表中重複記錄,只保留一條不重複數據

轉自:http://www.maomao365.com/?p=4942數據庫

下文主要講述:重複數據只獲取一條的方法函數

row_number函數在數據庫中的功能是爲每一行 按照必定的規則生成一個編號,
咱們經常利用這一屬性,對錶進行分頁操做,下文咱們將講述採用 row_number函數刪除表中重複數據行spa

/*建表*/
create table A(keyId int,info varchar(20)) go 
/*生成數據*/
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


/*刪除 keyId重複數據 中的另外幾條*/
delete [A2] from (select row_number() over (Partition By keyId order by keyId) as keyId2,* from A ) as [A2]
where [A2].keyId2  >1 
 

/* /*刪除 全部列都重複數據 中的另外幾條*/
delete [A2] from (select row_number() over (Partition By keyId,info order by keyId) as keyId2,* from A ) as [A2]
where [A2].keyId2  >1 
 */

/*展現刪除後的數據*/

select * from A go

truncate table A drop table A go
相關文章
相關標籤/搜索