SQL查询多条不重复记录值简要解析【转载】

转载http://hi.baidu.com/my_favourate/item/3716b0cbe125f312505058eb

SQL查询多条不重复记录值简要解析2008-02-28 11:36 以下内容在Oracle 10g下测试
由于设计需要,需要查询不重复的记录值,同类问题,想必大家都遇到过,于是乎马上GOOGLE一下,发现此类问题还挺多,解决方案也不少,仔细看看。
例如有如下表结构和值
table
fid   name sex
1     a      男
2     b      男
3     c      女
4     d      女
5     a      男
6     b      男
方案一:distinct
select distinct name from table
得到结果:
name
a
b
c
d
实现效果,那如果要同时打开其它记录呢?再试试
select distinct name,id from table
测试没什么效果,查下得知,这样实际是要name和id字段都重复才被筛选。继续查找可得如下方法:
方案二:group by
select *, count(distinct name) from table group by name

Oracle下测试失败,据说MYSQL下通过,不管,继续思考....
翻翻书,试试
select min(fid),name,sex from table group by name
成功,现实如下结果:
fid   name sex
1     a      男
2     b      男
3     c      女
4     d      女
继续思考,如果要打开所有记录,不指定字段用(*),貌似这方法就不行了!
select * from table where fid in(Select min(fid) FROM table group by name)
测试成功
fid   name sex
1     a      男
2     b      男
3     c      女
4     d      女
方案三:
本来已经完了,突然想起前几天在网上查了查询数据中所有某字段重复的记录
select   *   from   table   where   name in(select   name   from   table   group   by   name     having   count(name)=2) 
得到如下结果:
fid   name sex
1     a      男
2     b      男
5     a      男
6     b      男
以此类推:
select   *   from   table   where   name in(select   name   from   table   group   by   name     having   count(name)=1)
按道理说没问题,大家试试~~
再多的字段都全部现实。哎,原来如此简单!回顾网上方法distinct,Inner   Join等等,麻烦,而且有很大局限性.
总结如下:
select distinct name from table打开重复记录的单个字段
select * from table where fid in(Select min(fid) FROM table group by name)打开重复记录的所有字段值
select   *   from   table   where   name in(select   name   from   table   group   by   name     having   count(name)=1)打开重复任意次数的所有记录

在几千条记录里,存在着些相同的记录,如何能用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 peopleId   in (select   peopleId   from people   group   by   peopleId having   count(peopleId) > 1)
and rowid not in (select min(rowid) from   people   group by peopleId   having count(peopleId )>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)

比方说在A表中存在一个字段“name”,而且不同记录之间的“name”值有可能会相同,
现在就是需要查询出在该表中的各记录之间,“name”值存在重复的项;
Select Name,Count(*) From A Group By Name Having Count(*) > 1

原文地址:https://www.cnblogs.com/lydialee/p/4331069.html