rank over

本贴最后更新于 2516 天前,其中的信息可能已经时移世易

返回各部门工资排名前三位的员工

有表 SCOTT.EMP 如下:

现在要求返回各部门(DEPTNO)工资(SAL)排名前三位的员工(ENAME)

第一步:

SELECT DEPTNO,ENAME,SAL,
  DENSE_RANK() OVER(PARTITION BY DEPTNO ORDER BY SAL DESC) AS DENSE_RANK 
  -- DENSE_RANK分析函数,PARTITION分组子句
FROM SCOTT.EMP

结果为:

第二步:过滤出前三名

WITH A AS
 (SELECT DEPTNO,ENAME,SAL,
	DENSE_RANK() OVER(PARTITION BY DEPTNO ORDER BY SAL DESC) AS DENSE_RANK 
	-- DENSE_RANK分析函数,PARTITION分组子句
    FROM SCOTT.EMP)
SELECT DEPTNO, ENAME, SAL FROM A WHERE DENSE_RANK <= 3;

备注:把 DENSE_RANK 改成 RANK

SELECT DEPTNO,ENAME,SAL,
  RANK() OVER(PARTITION BY DEPTNO ORDER BY SAL DESC) AS DENSE_RANK 
  FROM SCOTT.EMP

这个结果为:

附加:DENSE_RANK 的官方定义

  • DENSE_RANK computes the rank of a row in an ordered group of rows and returns the rank as a NUMBER. The ranks are consecutive(连续的) integers beginning with 1. The largest rank value is the number of unique values returned by the query. Rank values are not skipped(跳跃) in the event of ties(结). Rows with equal values for the ranking criteria(条件) receive the same rank. This function is useful for top-N and bottom-N reporting.

  • This function accepts as arguments any numeric datatype and returns NUMBER.

  • As an aggregate(聚集) function, DENSE_RANK calculates the dense(密集的) rank of a hypothetical(假设的) row identified by the arguments of the function with respect to a given sort specification(规格). The arguments of the function must all evaluate(评价) to constant expressions within each aggregate group, because they identify a single row within each group. The constant argument expressions and the expressions in the order_by_clause of the aggregate match by position. Therefore, the number of arguments must be the same and types must be compatible.

  • As an analytic function, DENSE_RANK computes the rank of each row returned from a query with respect to the other rows, based on the values of the value_exprs in the order_by_clause.

  • 数据库

    据说 99% 的性能瓶颈都在数据库。

    330 引用 • 614 回帖

相关帖子

回帖

欢迎来到这里!

我们正在构建一个小众社区,大家在这里相互信任,以平等 • 自由 • 奔放的价值观进行分享交流。最终,希望大家能够找到与自己志同道合的伙伴,共同成长。

注册 关于
请输入回帖内容 ...