mysql查询top5_用一条SQL查询Top5与其它的总和

比如表

name

count

A

10

B

5

C

20

D

60

E

80

F

2

G

7

H

3

共8条记录

name保证唯一

现在要查询count的TOP5,以及剩下3条的总和:

name

count

E

80

D

60

C

20

A

10

G

7

其它 10

MySQL

select * from (select * from 比如表 order bycountdesc limit 5) t union all select '其它',sum(count) from 比如表 where name not in (select name from 比如表 order bycountdesc limit 5)

Oracle 不支持 TOP 关键字:不过这个好像并不十分严重,因为它提供了 rownum 这个隐式游标,可以实现与 TOP 类似的功能,如:

SELECT TOP 10 ... FROM WHERE ...

要写成

SELECT ... FROM ... WHERE ... AND rownum <= 10

oracle分页

-- 不能对ROWNUM使用>(大于1的数值)、>=(大于或等于1的数值)、=(大于或等于1的数值),否则无结果

-- 所以直接用只能从1开始

-- rownum >10 没有记录,因为第一条不满足去掉的话,第二条的rownum又成了1,所以永远没有满足条件的记录。

select * from student where rownum>=1;

--如果想要用rownum不从1开始,需按下面方法使用

select a1.* from (select student.*,rownum rn from student) a1 where rn >5;

--分页查询一

select * from (select a1.*,rownum rn from (select * from student) a1 where rownum <=5) where rn>=2;

--分页查询二

select a1.* from (select student.*,rownum rn from student where rownum <=5) a1 where rn >=3;

--分页查询三

select a1.* from (select student.*,rownum rn from student) a1 where rn between 3 and 5;

  • 2
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值