分析函数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
總結
以上是生活随笔為你收集整理的分析函数RANK的使用的全部內容,希望文章能夠幫你解決所遇到的問題。