1.rank() over:查出指定条件后的进行排名。特点是,加入是对学生排名,使用这个函数,成绩相同的两名是并列,下一位同学空出所占的名次。
SELECT name,subject,score,
RANK() OVER(PARTITION BY subject ORDER BY score DESC) AS rank
FROM student_score;
2.dense_rank() over:与rank() over的區别是,两名学生的成绩并列以后,下一位同学并不空出所占的名次。
SELECT name,subject,score,
DENSE_RANK() OVER(PARTITION BY subject ORDER BY score DESC) AS rank
FROM student_score;
3.row_number() over这个函数不需要考虑是否并列,哪怕根据条件查询出来的数值相同也会进行连续排名
SELECT name,subject,score,
ROW_NUMBER() OVER(PARTITION BY subject ORDER BY score DESC) AS rank
FROM student_score;
4.使用rank() over的时候,空值是最大的,如果排序字段为null,可能造成null字段排在最前面,影响排序结果。可以这样来规避这个问题。
SELECT name,subject,score,
RANK() OVER(PARTITION BY subject ORDER BY score DESC NULLS last) AS rank
FROM student_score;