日期:2014-05-18  浏览次数:20540 次

求sql语句,去掉id号小的重复记录
要求删除表中name重复的id号小的那条记录,保留id号最大的那条。没有重复,不删除。
表名table1

id name
1 aa //后面重复删除
2 bb //无重复,不删除
3 cc //后面重复,删除
4 dd //无重复,不删除
5 cc //保留,重复,保留id号大的这个
6 aa //保留,重复,保留id号大的这个

结果:
2 bb
4 dd
5 cc
6 aa

谢谢!


------解决方案--------------------
写错了,修改一下 count(1)>1
delete from
table1 where id in( 
select min(id) as id from table1 group by name having count(1) >1)

-----
这个只针对最多有重复2个,如果有3个以上的重复的话可以执行
while @@rowcount<>0

delete from
table1 where id in( 
select min(id) as id from table1 group by name having count(1) >1)



------解决方案--------------------
SQL code

--try

delete tbName
where id not in(
    select max(id) from tbName group by name
)

------解决方案--------------------
delete from table1 where id not in 
( select max(id) id from table1 where name in(
select name from (select name,count(name) as ts from table1 group by name) t where ts <>1 
) group by name ) and name in (select name from (select name,count(name) as tt from table1 group by name) s
where tt <> 1)
试试看,应该可以了!!