SQL删除重复数据只保留一条

http://blog.csdn.net/anya/article/details/6407280/

用SQL语句,删除掉重复项只保留一条

在几千条记录里,存在着些相同的记录,如何能用SQL语句,删除掉重复的呢
1、查找表中多余的重复记录,重复记录是根据单个字段(peopleId)来判断 
select * from people 
where peopleId in (select peopleId from people group by peopleId having count(peopleId) > 1) 

2、删除表中多余的重复记录,重复记录是根据单个字段(peopleId)来判断,只留有rowid最小的记录 
delete from people 
where   peopleName in (select peopleName    from people group by peopleName      having count(peopleName) > 1) 
and   peopleId not in (select min(peopleId) from people group by peopleName     having count(peopleName)>1) 

3、查找表中多余的重复记录(多个字段) 
select * from vitae a 
where (a.peopleId,a.seq) in (select peopleId,seq from vitae group by peopleId,seq having count(*) > 1) 

4、删除表中多余的重复记录(多个字段),只留有rowid最小的记录 
delete from vitae a 
where (a.peopleId,a.seq) in (select peopleId,seq from vitae group by peopleId,seq having count(*) > 1) 
and rowid not in (select min(rowid) from vitae group by peopleId,seq having count(*)>1) 

5、查找表中多余的重复记录(多个字段),不包含rowid最小的记录 
select * from vitae a 
where (a.peopleId,a.seq) in (select peopleId,seq from vitae group by peopleId,seq having count(*) > 1) 
and rowid not in (select min(rowid) from vitae group by peopleId,seq having count(*)>1)   

6.消除一个字段的左边的第一位:

update tableName set [Title]=Right([Title],(len([Title])-1)) where Title like '村%'

7.消除一个字段的右边的第一位:

update tableName set [Title]=left([Title],(len([Title])-1)) where Title like '%村'

8.假删除表中多余的重复记录(多个字段),不包含rowid最小的记录 
update vitae set ispass=-1
where peopleId in (select peopleId from vitae group by peopleId

1.查询重复记录

select * from 表名
where 重复字段 in (select  重复字段 from  表名  group  by  重复字段 having  count(重复字段) > 1)

2.删除保留一条重复记录

delete from 表名
where 重复字段  in (select  重复字段 from 表名 group  by  重复字段   having  count(重复字段) > 1)
and ID not in (select min(ID) from  表名  group by 重复字段 having count(重复字段 )>1)

    前一阵做了个会员系统,又写了个程序把以往的会员数据导入到SQL数据库中.因为某些原因导了好几遍,造成了某些重复的记录存在.前两天使用人员才发现问题,于是想办法解决.
    搜啊搜,搜到了使用SQL句子删除重复记录的方法.又一次体会到了SQL的强大(其实是我的SQL水平太菜了而已).写下来,加强记忆.
    会员数据需要用到的是下面三个字段:ID(自增),MemberName,MemberAddress.只要会员姓名与会员地址相同就认为是重复记录,重复记录在删除时只保留ID最大的那个.SQL如下:
    

delete MemberInfo where ID not in (
  select max(ID) from MemberInfo group by MemberName, MemberAddress)

    not in的效率可能会低些,但因为是直接操作数据库,所以这并不重要.这个句子还是非常的简单有效的.
    
    在真正的删除操作前,通常会先了解一下重复记录的情况.可以使用下面的句子:
    

SELECT COUNT(MemberName) AS TheCount, MemberName, MemberAddress
FROM MemberInfo
GROUP BY MemberName, MemberAddress
HAVING (COUNT(*) > 1)

    因为工作中用的SQL太简单,以至于group by及having的用法都不了解,真是惭愧.
    P.S. 所有的内容都来自于网络,没有什么独创的东西.发出来只是为了加强一下自己的记忆.

原文地址:https://www.cnblogs.com/chengjun/p/6136219.html