如何删除数据库一个表中某列是重复的数据?

如何删除数据库一个表中某列是重复的数据?

比如表T:
id    name
1     aa
2     bb
3     cc
4     aa
5     aa
6     cc

如何变成(保留最大的id或者最小的id):
id    name
1     aa
2     bb
3     cc

1.使用distinct关键字,导出无重复的数据到一个临时表,删除原表,再从临时表导入数据:
select distinct name into #temp from T
drop table T
select identity(int,1,1) as id, * into T from #temp
drop table #temp
如果原表的id和其他表没有联系并只有id,name列时,用这种方法可以,当然最好原表数据不要太多。

2.不用distinct关键字,导出无重复的数据到一个临时表,删除原表,再从临时表导入数据:
select name into #temp from T where id in (select max(id) from aa group by name)
drop table T
select identity(int,1,1) as id, * into T from #temp
drop table #temp

3.使用delete语句,把name相同的类中id最大(或者最小)的数据删掉,循环执行,直到受影响的行数是0:
delete from T where id in (select max(id) from T group by name having count(*)>1)

4.还是delete语句,把除了name相同的类中最大的id(或者最小)的数据删掉,执行一次即可:
delete from T where id not in   (select max(id) from T group by name )
原文地址:https://www.cnblogs.com/ygm900/p/3464573.html