oracle mysql top_oracle/mysql TOP/Button N查询

oracle里面要获取每个分组里面的topN可以采用:

select *

from (select emp_id, name, occupation,

rank() over ( partition by occupation order by emp_id) rank

from employee)

where rank <= 3

select * from

(select emp_id, name, occupation,rank() over (

partition by occupation order by emp_id,RowNum) rank

from employee)

where rank <= 3

mysql:分组之后取topN的sql:

Here’s another form of the solution without subquery that also resolves matching ratings by using the primary key:

DROP DATABASE IF EXISTS topn;

CREATE DATABASE topn;

USE topn;

CREATE TABLE theTable (

pKey int PRIMARY KEY

, groupId int

, rating int

);

INSERT INTO theTable (

pKey

, groupId

, rating

) VALUES

( 1, 1, 55 )

, ( 2, 1, 53 )

, ( 3, 1, 51 )

, ( 4, 1, 59 )

, ( 5, 1, 58 )

, ( 6, 1, 58 )

, ( 7, 1, 53 )

, ( 8, 1, 55 )

, ( 9, 1, 55 )

, ( 10, 1, 53 )

, ( 11, 2, 52 )

, ( 12, 2, 53 )

, ( 13, 2, 54 )

, ( 14, 2, 59 )

, ( 15, 2, 58 )

, ( 16, 2, 57 )

, ( 17, 2, 56 )

;

SELECT t1.pKey

, t1.rating

, t1.groupId

, COUNT(t2.pKey) AS cnt

FROM theTable AS t1

LEFT JOIN theTable AS t2

ON (t1.rating, t1.pKey) <= (t2.rating, t2.pKey)

AND t1.groupId = t2.groupId

GROUP BY t1.pKey

, t1.rating

, t1.groupId

HAVING cnt <= 5

ORDER BY t1.groupId, cnt

;

查询结果:

03e8680445837a2b3a2e624be099aca9.png

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值