分析函数RANK的使用

有这么一个表table1

username  subject  score

张三     语文    80
张三     数学    90
张三     英语    88
李四     语文    90
李四     数学    92
李四     英语    94
王五     语文    62
王五     数学    96
王五     英语    76

现在要按科目排名次,得到如下结果:

username  subject  score  level

张三     语文    80   2
张三     数学    90   3
张三     英语    88   2
李四     语文    90   1
李四     数学    92   2
李四     英语    94   1
王五     语文    62   3
王五     数学    96   1
王五     英语    76   3
……

那么sql要这么写:select username,subject,score,RANK() OVER (PARTITION BY subject ORDER BY score desc) level from table1

只取每门科目头3名的记录:select * from (select username,subject,score,RANK() OVER (PARTITION BY subject ORDER BY score desc) level from table1) where level<=3

RANK() OVER (PARTITION BY subject ORDER BY score desc) 的意思是按照subject分组对score进行排序
和RANK类似的还有DENSE_RANK,只是遇到排名相同的情况,RANK有跳跃,DENSE_RANK没有跳跃

分析函数FIRST_VALUE、LAST_VALUE

FIRST_VALUE、LAST_VALUE是两个分析函数,返回结果集中排在第一位和最后一位的值。语法是:FIRST_VALUE (expr) OVER ( analytic_clause)
如:select t.*,first_value(username) over(partition BY organid order by userid asc) from tbuser t

select t.*,first_value(username) over(order by userid asc) from tbuser t

转载于:https://www.cnblogs.com/xiaopeng84/archive/2009/03/16/1412887.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值