sql查询不重复记录:SQL重复记录查询来源: 发布时间:星期三, 2009年9月2日 浏览:2次 评论:0
1、查找表中多余重复记录重复记录是根据单个字段(peopleId)来判断
select*frompeople wherepeopleIdin(select peopleId from people group by peopleId having count(peopleId)>1) 2、删除表中多余重复记录重复记录是根据单个字段(peopleId)来判断只留有rowid最小记录 deletefrompeople wherepeopleId in(select peopleId frompeople group by peopleId having count(peopleId)>1) androwidnotin(selectmin(rowid)from people groupbypeopleId havingcount(peopleId )>1) 3、查找表中多余重复记录(多个字段) select*fromvitae a where(a.peopleId,a.seq)in (selectpeopleId,seqfromvitaegroupbypeopleId,seq havingcount(*)>1) 4、删除表中多余重复记录(多个字段)只留有rowid最小记录 deletefromvitae a where(a.peopleId,a.seq)in (selectpeopleId,seqfromvitaegroupbypeopleId,seqhavingcount(*)>1) androwidnotin(selectmin(rowid)fromvitaegroupbypeopleId,seqhavingcount(*)>1) 5、查找表中多余重复记录(多个字段)不包含rowid最小记录 select*fromvitae a where(a.peopleId,a.seq)in (selectpeopleId,seqfromvitaegroupbypeopleId,seqhavingcount(*)>1) androwidnotin(selectmin(rowid)fromvitaegroupbypeopleId,seqhavingcount(*)>1) ( 2) 比方说 在A表中存在个字段“name” 而且区别记录的间“name”值有可能会相同 现在就是需要查询出在该表中各记录的间“name”值存在重复项; SelectName,Count(*)FromAGroupByNameHavingCount(*)>1 如果还查性别也相同大则如下: SelectName,sex,Count(*)FromAGroupByName,sexHavingCount(*)>1 ( 3) 思路方法 declare@maxeger,@ideger declarecur_rowscursorlocalforselect主字段,count(*)from表名groupby主字段havingcount(*)>;1 opencur_rows fetchcur_rowso@id,@max while@@fetch_status=0 begin select@max=@max-1 rowcount@max deletefrom表名where主字段=@id fetchcur_rowso@id,@max end closecur_rows rowcount0 思路方法 2 有两个意义上重复记录是完全重复记录也即所有字段均重复记录 2是部分关键字段重复记录比如Name字段重复而其他字段不定重复或都重复可以忽略 1、对于第种重复比较容易解决使用 selectdistinct*fromtableName 就可以得到无重复记录结果集 如果该表需要删除重复记录(重复记录保留1条)可以按以下思路方法删除 selectdistinct*o#TmpfromtableName droptabletableName select*otableNamefrom#Tmp droptable#Tmp 发生这种重复原因是表设计不周产生增加唯索引列即可解决 2、这类重复问题通常要求保留重复记录中第条记录操作思路方法如下 假设有重复字段为Name,Address要求得到这两个字段唯结果集 selectidentity(,1,1)asautoID,*o#TmpfromtableName selectmin(autoID)asautoIDo#Tmp2from#TmpgroupbyName,autoID select*from#TmpwhereautoIDin(selectautoIDfrom#tmp2) 最后个select即得到了NameAddress不重复结果集(但多了个autoID字段实际写时可以写在select子句中省去此列) ( 4)查询重复 select*fromtablenamewhereidin( selectidfromtablename groupbyid havingcount(id)>1 ) 0
相关文章读者评论发表评论 |
|