Skip to content

Instantly share code, notes, and snippets.

@helanan
Created October 3, 2017 14:34
Show Gist options
  • Save helanan/dc9c3f8799bc4de643f4bc9679d2e2c5 to your computer and use it in GitHub Desktop.
Save helanan/dc9c3f8799bc4de643f4bc9679d2e2c5 to your computer and use it in GitHub Desktop.
A Dense Rank In Oracle
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.
Aggregate Example:
SELECT DENSE_RANK(15500, .05) WITHIN GROUP
(ORDER BY salary DESC, commission_pct) "Dense Rank"
FROM employees;
Dense Rank
-------------------
3
Analytic Example:
SELECT d.department_name, e.last_name, e.salary, DENSE_RANK()
OVER (PARTITION BY e.department_id ORDER BY e.salary) AS drank
FROM employees e, departments d
WHERE e.department_id = d.department_id
AND d.department_id IN ('30', '40');
DEPARTMENT_NAME LAST_NAME SALARY DRANK
----------------------- ------------------ ---------- ----------
Purchasing Colmenares 2500 1
Purchasing Himuro 2600 2
Purchasing Tobias 2800 3
Purchasing Baida 2900 4
Purchasing Khoo 3100 5
Purchasing Raphaely 11000 6
Human Resources Marvis 6500
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment