Oracle中rank() over, dense_rank(), row_number() 的区别

前端之家收集整理的这篇文章主要介绍了Oracle中rank() over, dense_rank(), row_number() 的区别前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

Oracle中rank() over,dense_rank(),row_number() 的区别@H_502_3@

假设现在有一张学生表student,学生表中有姓名、分数、课程编号,现在我需要按照课程对学生的成绩进行排序。@H_502_3@

select * from student@H_502_3@

@H_502_3@

1. rank over ()可以实现对学生排名,特点是成绩相同的两名是并列,如下1 2 2 4 5@H_502_3@

select name,
course,宋体; font-size:14px; line-height:22.4px; margin-bottom:0px; margin-left:0px; margin-right:0px; margin-top:0px; text-align:justify; width:auto; word-wrap:break-word"> rank() over(partition by course order by score desc) as rank
from student;@H_502_3@

@H_502_3@

2. dense_rank()和rank over()很像,但学生成绩并列后并不会空出并列所占的名次,如下1 2 2 3 4@H_502_3@

select name,宋体; font-size:14px; line-height:22.4px; margin-bottom:0px; margin-left:0px; margin-right:0px; margin-top:0px; text-align:justify; width:auto; word-wrap:break-word"> dense_rank() over(partition by course order by score desc) as rank
from student;@H_502_3@

@H_502_3@

3. row_number这个函数不需要考虑是否并列,那怕根据条件查询出来的数值相同也会进行连续排名@H_502_3@

select name,宋体; font-size:14px; line-height:22.4px; margin-bottom:0px; margin-left:0px; margin-right:0px; margin-top:0px; text-align:justify; width:auto; word-wrap:break-word"> row_number() over(partition by course order by score desc) as rank
from student;@H_502_3@

@H_502_3@


答疑:@H_502_3@

1. partition by用于给结果集进行分区。@H_502_3@

2. partition by和group by有何区别?@H_502_3@

partition by只是将原始数据进行名次排列(记录数不变)@H_502_3@


group by是对原始数据进行聚合统计(记录数可能变少,每组返回一条)@H_502_3@

3. 使用rank over()的时候,空值是最大的,如果排序字段为null,可能造成null字段排在最前面,影响排序结果。@H_502_3@

可以这样: rank over(partition by course order by score desc nulls last)@H_502_3@

更多Oracle相关信息见Oracle 专题页面 http://www.linuxidc.com/topicnews.aspx?tid=12@H_502_3@

本文永久更新链接地址http://www.linuxidc.com/Linux/2015-04/116349.htm@H_502_3@

猜你在找的Oracle相关文章