分析函数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