一、语法
- rank() over (order by 排序字段 顺序)
- rank() over (partition by 分区字段 order by 排序字段 顺序)
asc|desc 升序\降序
分区与分组有什么区别?
- 分区是将原始数据进行名次排列(记录数不变)
- 分组是对原始数据进行聚合统计(记录数变少,每组返回一条)
- rank 与 dense_rank的区别,rank()是非连续排名,dense_rank()是连续排名
二、实例
原始表:
- 非连续简单排名
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';
2.连续简单排名
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';
3.分区排名
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;
4.分区排名后加条件
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;
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