34,590
社区成员
发帖
与我相关
我的任务
分享
------------------------------------------------------------------------------
--Author:霜寒月冷
--VERSION: Microsoft SQL Server 2008 R2 (RTM) - 10.50.1600.1 (X64) Apr 2 2010 15:48:46 Copyright (c) Microsoft Corporation Standard Edition (64-bit) on Windows NT 5.2 <X64> (Build 3790: Service Pack 2)
--Creation Date: 01/08/14
--Last Modified: [09:00:32]
----------------------------建表------------------------------------------
if object_id('[tb]') is not null drop table [tb]
go
create table tb (id int,col varchar(10),col2 varchar(20) )
insert into tb
select 1,'111','222' union all
select 2,'111','222' union all
select 3,'111','222' union all
select 4,'111','222'
go
;with cte as
(
select * ,row_number() over (partition by col,col2 order by id desc) as rn from tb
)
delete from cte where rn<>1
go
select * from tb
----------------------------结果------------------------------------------
/*
id col col2
----------- ---------- --------------------
4 111 222
*/
------------------------------------------------------------------------------
--Author:霜寒月冷
--VERSION: Microsoft SQL Server 2008 R2 (RTM) - 10.50.1600.1 (X64) Apr 2 2010 15:48:46 Copyright (c) Microsoft Corporation Standard Edition (64-bit) on Windows NT 5.2 <X64> (Build 3790: Service Pack 2)
--Creation Date: 01/08/14
--Last Modified: [09:00:32]
----------------------------建表------------------------------------------
if object_id('[tb]') is not null drop table [tb]
go
create table tb (id int,col varchar(10),col2 varchar(20) )
insert into tb
select 1,'111','222' union all
select 2,'111','222' union all
select 3,'111','222' union all
select 4,'111','222'
go
delete from tb where id in
(
select id from (
select * ,row_number() over (partition by col,col2 order by id desc) as rn from tb ) t
where t.rn<>1
)
go
select * from tb
----------------------------结果------------------------------------------
/*
id col col2
----------- ---------- --------------------
4 111 222
*/