📜  oracle rank - SQL (1)

📅  最后修改于: 2023-12-03 15:03:23.887000             🧑  作者: Mango

Oracle Rank - SQL

The concept of ranking is often used in SQL operations to order the output of queries based on certain criteria. Oracle has introduced several functions to perform ranking operations, including RANK, DENSE_RANK, and ROW_NUMBER.

RANK Function

The RANK function assigns a unique rank to each distinct row based on the order specified in the ORDER BY clause. If two rows have equal values, they are assigned the same rank and the next rank is skipped.

Syntax:
RANK( ) OVER ([PARTITION BY partition_expression, ... ]
             ORDER BY order_expressions [ASC | DESC], ... )
Example:

Consider a table "employee" with the following data:

| ID | Name | Salary | |----|--------|--------| | 1 | John | 5000 | | 2 | Bob | 7500 | | 3 | Alice | 4000 | | 4 | Steven | 6000 |

SELECT Name, Salary, RANK() OVER (ORDER BY Salary DESC) AS Rank
FROM employee;

This query would produce the following output:

| Name | Salary | Rank | |--------|--------|------| | Bob | 7500 | 1 | | Steven | 6000 | 2 | | John | 5000 | 3 | | Alice | 4000 | 4 |

DENSE_RANK Function

The DENSE_RANK function assigns a unique rank to each distinct row based on the order specified in the ORDER BY clause. If two rows have equal values, they are assigned the same rank, with no gap between ranks.

Syntax:
DENSE_RANK( ) OVER ([PARTITION BY partition_expression, ... ]
             ORDER BY order_expressions [ASC | DESC], ... )
Example:

Consider a table "employee" with the following data:

| ID | Name | Salary | |----|--------|--------| | 1 | John | 5000 | | 2 | Bob | 7500 | | 3 | Alice | 4000 | | 4 | Steven | 6000 |

SELECT Name, Salary, DENSE_RANK() OVER (ORDER BY Salary DESC) AS Dense_Rank
FROM employee;

This query would produce the following output:

| Name | Salary | Dense_Rank | |--------|--------|------------| | Bob | 7500 | 1 | | Steven | 6000 | 2 | | John | 5000 | 3 | | Alice | 4000 | 4 |

ROW_NUMBER Function

The ROW_NUMBER function assigns a unique sequential number to each row in the result set, based on the order specified in the ORDER BY clause.

Syntax:
ROW_NUMBER( ) OVER ([PARTITION BY partition_expression, ... ]
             ORDER BY order_expressions [ASC | DESC], ... )
Example:

Consider a table "employee" with the following data:

| ID | Name | Salary | |----|--------|--------| | 1 | John | 5000 | | 2 | Bob | 7500 | | 3 | Alice | 4000 | | 4 | Steven | 6000 |

SELECT Name, Salary, ROW_NUMBER() OVER (ORDER BY Salary DESC) AS Row_Num
FROM employee;

This query would produce the following output:

| Name | Salary | Row_Num | |--------|--------|---------| | Bob | 7500 | 1 | | Steven | 6000 | 2 | | John | 5000 | 3 | | Alice | 4000 | 4 |

In conclusion, the Oracle Rank functions are very useful in SQL operations where ranking is required. The RANK, DENSE_RANK, and ROW_NUMBER functions work together to provide flexibility in generating output based on ranking criteria.