Home >Database >Mysql Tutorial >Oracle中rank() over, dense_rank(), row_number() 的区别

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

WBOY
WBOYOriginal
2016-06-07 16:07:311720browse

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

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

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

select * from student

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

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

select name,
      course,
      rank() over(partition by course order by score desc) as rank
  from student;

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

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

select name,
      course,
      dense_rank() over(partition by course order by score desc) as rank
  from student;

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

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

select name,
      course,
      row_number() over(partition by course order by score desc) as rank
  from student;

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


答疑:

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

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

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


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

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

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

本文永久更新链接地址

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn