Ranking functions in SQL are useful for performing analytical queries and obtaining rankings based on specified criteria. Here are some commonly used SQL ranking functions:
ROW_NUMBER():
Assigns a unique number to each row based on the specified order.
SELECTÂ employee_id, salary, ROW_NUMBER() OVERÂ (ORDERÂ BYÂ salary DESC) ASÂ rank FROMÂ employees; |
RANK():
Assigns a rank to each row, with ties receiving the same rank, and leaving gaps in the ranking sequence.
SELECTÂ department, AVG(salary), RANK() OVERÂ (ORDERÂ BYÂ AVG(salary) DESC) ASÂ department_rank FROMÂ employees GROUPÂ BYÂ department; |
DENSE_RANK():
Similar to RANK(), but without gaps in the ranking sequence for tied values.
SELECTÂ department, AVG(salary), DENSE_RANK() OVERÂ (ORDERÂ BYÂ AVG(salary) DESC) ASÂ department_dense_rank FROMÂ employees GROUPÂ BYÂ department; |
NTILE():
Divides the result set into a specified number of roughly equal groups and assigns a group number to each row.
SELECTÂ employee_id, salary, NTILE(4) OVERÂ (ORDERÂ BYÂ salary DESC) ASÂ salary_quartile FROMÂ employees; |
PERCENT_RANK():
Calculates the relative rank of each row as a percentage.
SELECTÂ department, AVG(salary), PERCENT_RANK() OVERÂ (ORDERÂ BYÂ AVG(salary) DESC) ASÂ department_percent_rank FROMÂ employees GROUPÂ BYÂ department; |
CUME_DIST():
Calculates the cumulative distribution of a value within a group.
SELECTÂ department, AVG(salary), CUME_DIST() OVERÂ (ORDERÂ BYÂ AVG(salary) DESC) ASÂ department_cume_dist FROMÂ employees GROUPÂ BYÂ department; |
These ranking functions are part of the SQL window functions category and are particularly useful in analytical queries where you need to assign ranks or calculate distribution percentages based on certain criteria. Always adapt these queries to the specific requirements and structure of your dataset and database.
Comments