rank用法

一、語法

  • rank() over (order by 排序字段 順序)
  • rank() over (partition by 分區(qū)字段 order by 排序字段 順序)

asc|desc 升序\降序

分區(qū)分組有什么區(qū)別?

  • 分區(qū)是將原始數(shù)據(jù)進行名次排列(記錄數(shù)不變)
  • 分組是對原始數(shù)據(jù)進行聚合統(tǒng)計(記錄數(shù)變少,每組返回一條)
  • rank 與 dense_rank的區(qū)別,rank()是非連續(xù)排名,dense_rank()是連續(xù)排名

二、實例

原始表:


s1.png
  1. 非連續(xù)簡單排名
select sc.s_id,sc.s_name,sc.sub_name,sc.score,
   rank() over (order by score desc) 名次
   from t_score sc
   where sc.sub_name = 'oracle';
s2.png

2.連續(xù)簡單排名

select sc.s_id,sc.s_name,sc.sub_name,sc.score,
   dense_rank() over (order by score desc) 名次
   from t_score sc
   where sc.sub_name = 'oracle';
s3.png

3.分區(qū)排名

SELECT sc.s_id,sc.s_name,sc.sub_name,sc.score,
   RANK() OVER(partition by sub_name order by score desc) 名次
   from t_score sc;
s4.png

4.分區(qū)排名后加條件

SELECT * from(
   SELECT sc.s_id,sc.s_name,sc.sub_name,sc.score,
      DENSE_RANK() OVER(partition by sub_name order by score desc) 名次
      FROM t_score sc) X
   WHERE x.名次 <= 2;
s5.png

5.匯總后排名

SELECT x.*,
   RANK() OVER (order by sum_score desc) 名次
   FROM(
      SELECT s_id,s_name,sum(score) sum_score from t_score group by s_id,s_name) x
s6.png
?著作權歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關閱讀更多精彩內(nèi)容

  • 分析函數(shù),也稱為窗口函數(shù),通常被認為僅對數(shù)據(jù)倉庫SQL有用。使用分析函數(shù)的查詢,基于對數(shù)據(jù)行的分組來計算總量值。與...
    貓貓_tomluo閱讀 3,468評論 3 18
  • row_number的用途非常廣泛,排序最好用它,它會為查詢出來的每一行記錄生成一個序號,依次排序且不會重復,注意...
    奶茶007閱讀 1,375評論 0 1
  • 2017/3/14 RDBMS:關系型數(shù)據(jù)庫管理系統(tǒng) 關系模型獨立于語言 SQL有幾種不同類型的語言:數(shù)據(jù)定義語言...
    ancherl閱讀 1,796評論 0 6
  • 這是很早之前面的,第一次面數(shù)據(jù)分析的面試,當時還傻乎乎的以為數(shù)據(jù)分析和數(shù)據(jù)挖掘是一回事呢。結(jié)果才發(fā)現(xiàn),數(shù)據(jù)分析崗位...
    文哥的學習日記閱讀 7,475評論 4 9
  • 轉(zhuǎn)載自:http://blog.csdn.net/ly0309/article/details/7008008 R...
    Hanswanglin閱讀 5,595評論 0 1

友情鏈接更多精彩內(nèi)容