sql 删除重复数据,保留重复最小ID
原创
©著作权归作者所有:来自51CTO博客作者guochunyang2004的原创作品,请联系作者获取转载授权,否则将追究法律责任
ID
Name
1
a
2
b
3
a
4
b
5
c
6 d
-- --标准sql方法:mysql、sql server--
-- 查询重复 方法一
select t.id,t.name from test t join(
select min(id) id,name from test group by name having(count(1)>1)
) tt on t.id>tt.id and t.name=tt.name
-- 查询重复 方法二
select * from test where exists(
select * from (
select min(id) id,name from test group by name having(count(1)>1)
) as tt where test.id>tt.id and test.name=tt.name
)
-- 删除重复 方法
delete from test where exists(
select * from (
select min(id) id,name from test group by name having(count(1)>1)
) as tt where test.id>tt.id and test.name=tt.name
)
-- --sql server方法----
-- 查询
select * from (
select ROW_NUMBER() over(partition by name order by id ) row,id,name from test
) t where t.row>1
-- 删除
delete from test where exists(
select * from
(
select ROW_NUMBER() over(partition by name order by id ) row,id,name from test
) t where t.row>1 and test.id=t.id
)
ID
Name
1
a
2
b
5
c
6
d