22,207
社区成员
发帖
与我相关
我的任务
分享
delete tb where ID(唯一) in
(select ID(唯一) from tb group by id+name having count(1)>1 and ID(唯一)>min(ID(唯一))
create table tab(ident int identity(1,1),id int,name nvarchar(10)) --其他字段不管
insert into tab select 1,'中国'
insert into tab select 2,'韩国'
insert into tab select 1,'中国'
insert into tab select 3,'印度'
insert into tab select 4,'德国'
insert into tab select 2,'韩国'
insert into tab select 2,'韩国'
go
select * from tab
/*
ident id name
----------- ----------- ----------
1 1 中国
2 2 韩国
3 1 中国
4 3 印度
5 4 德国
6 2 韩国
7 2 韩国
*/
go
delete tab from tab a where exists(select 1 from tab where id=a.id and ident <a.ident)
go
select * from tab
/*
ident id name
----------- ----------- ----------
1 1 中国
2 2 韩国
4 3 印度
5 4 德国
(4 行受影响)
*/
go
drop table tab
create table tab(ident int identity(1,1),id int,name nvarchar(10)) --其他字段不管
insert into tab select 1,'中国'
insert into tab select 2,'韩国'
insert into tab select 1,'中国'
insert into tab select 3,'印度'
insert into tab select 4,'德国'
insert into tab select 2,'韩国'
insert into tab select 2,'韩国'
go
select * from tab
/*
ident id name
----------- ----------- ----------
1 1 中国
2 2 韩国
3 1 中国
4 3 印度
5 4 德国
6 2 韩国
7 2 韩国
*/
go
delete tab from tab a where exists(select 1 from tab where id=a.id and ident >a.ident)
go
select * from tab
/*
ident id name
----------- ----------- ----------
3 1 中国
4 3 印度
5 4 德国
7 2 韩国
(4 行受影响)
*/
go
drop table tab
declare @table table (id int,col1 varchar(1),name varchar(4),col2 varchar(1),col3 varchar(1))
insert into @table
select 1,'a','中国','a','a' union all
select 2,'b','韩国','b','b' union all
select 1,'c','中国','c','c' union all
select 3,'d','印度','d','d' union all
select 4,'e','德国','e','e' union all
select 2,'f','韩国','f','f' union all
select 2,'h','韩国','h','h'
select id,MIN(col1) AS col1,[name],
MIN(col2) AS col3 ,MIN(col3) AS col3 from @table GROUP BY id,[name]
ORDER BY id
/*
id col1 name col3 col3
----------- ---- ---- ---- ----
1 a 中国 a a
2 b 韩国 b b
3 d 印度 d d
4 e 德国 e e
*/
select min(id),name from tb group by name