SQL的四大排名函数

row_number()

根据列为结果集中的行返回有序数字

select employeeID,row_number()over (order by salary asc) as Rank  from employee 查询结果会有一个Rank列,内容是从上到下1,2,3,4.....

rank()

根据指定条件在结果集中返回每一行的排名

select employeeID,rank()over (order by salary asc) as Rank  from employee 查询结果会有一个Rank列,内容是从上到下1,2,3,3,5,6.....

dense_rank()

根据指定条件给出连续排名值得情况

select employeeID,dense_rank()over (order by salary asc) as Rank  from employee 查询结果会有一个Rank列,内容是从上到下1,2,3,3,4,5,6.....

ntile()

将结果集划分为特定数量的组

select employeeID,ntile(4)over (order by salary asc) as Rank  from employee 将记录平均分为四组,第一组的rank列全为1,1,..

附加:dense_rank()也可以实现分组排序,先分组,然后进行分组排序,但要借助PARTITION BY

select employeeID,dense_rank()over (PARTITION BY managerID order by salary asc) as Rank  from employee where managerID  is not null

猜你喜欢

转载自blog.csdn.net/qq_33420835/article/details/82729808