SQL查询,如何去除重复的记录?
评论ID 文章AID 用户UID
1 20 1
2 20 2
3 30 1
4 30 3
5 30 1
6 40 5
如果想得到某个文章aid对应有多少条有效评论,sql查询怎么写?请注意,每个AID每个用户重复评论只计算一条有效,比如上面的数据应该是5条有效评论,aid为30的文章有一个用户发了2条评论,去掉一个重复。 展开
首先,先说明一个问题。这样的结果出现,说明系统设计是有问题的。
其次
删除重复数据,你要提供你是什么数据库。
不同数据库会有不同的解决方案。
关键字Distinct 去除重复,如下列SQL,去除Test相同的记录;
1. select distinct Test from Table
2. 如果是要删除表中存在的重复记录,那就逻辑处理,如下:
3. select Test from Table group by Test having count(test)>1
4. 先查询存在重复的数据,后面根据条件删除
还有一个更简单的方法可以尝试一下:
select aid, count(distinct uid) from 表名 group by aid
这是sqlserver 的写法。
如图一在数据表中有两个膀胱冲洗重复的记录。
2
可以通过sql语句“select *from 表名 where 编码 in(select 编码 from 表名 group by 编码 having count(1) >= 2)”来查询出变种所有重复的记录如图二
3
通过sql语句"
delete from 表名 where
编码 in(select 编码 from 表名 group by 编码 having count(1) >= 2)
and 编码 not in (select max(编码)from 表名 group by 编码 having count(1) >=2)
"来删除重复的记录只保留编码最大的记录
2016-01-03 · 做真实的自己 用良心做教育
关键字Distinct 去除重复,如下列SQL,去除Test相同的记录;
select distinct Test from Table
如果是要删除表中存在的重复记录,那就逻辑处理,如下:
select Test from Table group by Test having count(test)>1
先查询存在重复的数据,后面根据条件删除
sql 单表/多表查询去除重复记录
单表distinct
多表group by
group by 必须放在 order by 和 limit之前,不然会报错
************************************************************************************
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(*)>
select aid, count(distinct uid) from 表名 group by aid
这是sqlserver 的写法。。。
#查询班级中名字不同的所有学生(将名字相同的学生,只取出一个)
select * from student where sid in (select max(sid) from student group by sname)
#查询班级中所有名字重复的学生姓名
select * from student where sname in (select sname from student group by sname having count(1)>=2 );