1.Oracle某个表中有重复记录,想重复记录只显示一条。
表中内容如下:
ID Name score
1 | zs | 40.00 |
1 | zs | 40.00 |
1 | zs | 40.00 |
2 | ls | 80.00 |
2 | ls | 80.00 |
3 | ww | 90.00 |
3 | ww | 90.00 |
4 | zl | 100.00 |
用rowid写个最容易懂的:
select * from t_temp where rowid in(
select max(rowid) from t_temp group by id)
order by id;
显示结果:
ID Name score
1 | zs | 40.00 |
2 | ls | 80.00 |
3 | ww | 90.00 |
4 | zl | 100.00 |
最好是这么写,显示结果是一样的,效率要高很多:
with x as (
select max(rowid) r from t_temp group by id)
select t.id,t.name,t.score from t_temp t,x
where t.rowid = x.r
order by t.id;
2. 查询表中的重复记录。
select * from t_temp t,(select id from t_temp group by id having count(1)>1) x
where t.id=x.id
order by t.id
显示结果:
ID Name score
1 | zs | 40.00 |
1 | zs | 40.00 |
1 | zs | 40.00 |
2 | ls | 80.00 |
2 | ls | 80.00 |
3 | ww | 90.00 |
3 | ww | 90.00 |
3. 有另外一张表:t_temp2
ID ClassNM
1 | class1 |
2 | class2 |
3 | class3 |
4 | class4 |
这里的ID跟上张表的ID是一个概念。
现在要求查询出第二张表中所有的人,按照第一张表的重复出现条数进行排序显示(也就是要看每个人都重复了几次,都是哪个班的)。显示结果如下。
ID ClassNM NUM
1 | class1 | 3 |
2 | class1 | 2 |
3 | class2 | 2 |
4 | class4 | 1 |
SQL语语如下哦。
with x as(select count(id) num, id from t_temp group by id)
select t2.id,t2.classnm,x.num from t_temp2 t2,x
where t2.id=x.id
order by x.num desc,id asc
好记忆赶不上滥笔头,真是的。