一、語法
- 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
- 非連續(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