SQL 删除 某一字段重复值的记录

来源:百度知道 编辑:UC知道 时间:2024/06/18 16:52:38
表中有几个字段,现在想把id字段中的重复值的整条记录删除(相同id的其他字段值有不一样的,不过我只想要id保留唯一值 别的字段保留哪条的无所谓)。建临时表也行 请问怎样做

生成一个#tmptable的临时表
select id,max(field1),max(field2),max(field3) ..... into #tmptable from tablename group by id

这个问题不错,
假设你的字段里面除了id int型以外 还有一项是name varchar型
select distinct id into 临时表 from 表名
delete from 表名 where cast(id as varchar)+name not in
(select cast(id as varchar)+(select top 1 name from 表名 where id = 临时表.id) from 临时表)
drop table 临时表

这个方法可以让你实现你想要的结果。

1.一定要记住数据库设计的原则,每个表都要有主关键字,你出现的问题就是没有这个主关键字造成的.

2.既然已经发生了,解决的方法之一是对故障表按所有字段分组输出到临时表,临时表中的数据就是没有重复的,再回复即可.

你一定要有一个字段(或几个字段拼接成的字段)能唯一标识一条记录.
假设id加name能做主键
然后
select distinct id into #temp from tablename
delete from tablename where cast(id as varchar)+name not in
(select cast(id as varchar)+(select top 1 name from tablename where id = A.id) as idname from #temp A)

假设表名称为A,字段ID是有重复值,rid为唯一ID,没有的话可以新加一列让他为自增值就可以
sql语句:
delete from 表 where rid in (
select b.rid from 表 a inner join 表 b on a.id=b.id where a.ri