注册一亩三分地论坛,查看更多干货!
您需要 登录 才可以下载或查看附件。没有帐号?注册账号 
x
分享一下,在面试里被问到的,关于几个rank的区别
简而言之:
row_number 会返回unique value 1,2,3没有重复
rank会平等地处理相同的value,但是会考虑前面到底有几行,like,1,1,3
dense_rank 会有重复并且它一定有1,2,3 like 1,1,2,2,2,3,3
SQL ranking functions are window functions that assign a numeric rank to rows in a result set, often based on an ordering within a specified partition (or the entire result set if no partitioning is defined). The most commonly used ones are ROW_NUMBER(), RANK(), DENSE_RANK(), and occasionally NTILE(). Each provides a slightly different ranking behavior.
Below is a comprehensive overview of how they differ, how to use them, and some common scenarios where they’re helpful.Common Ranking Functions
- ROW_NUMBER()Syntax example:
- sqlCopy codeSELECT
- employee_id,
- salary,
- ROW_NUMBER() OVER (ORDER BY salary DESC) AS row_num
- FROM employees;
复制代码 - Definition: Assigns a unique sequential integer to each row within a partition of a result set, starting at 1. If you want each row to be uniquely identified regardless of ties, ROW_NUMBER() is your go-to.
- Behavior with ties: Each tied row gets a unique next number. For example, if two rows are tied for first place, the first one encountered might get a row_number of 1 and the second one would get 2.
- Example use case:
- Paginating large result sets (e.g., selecting rows 51–100).
- Selecting the "top N" rows from a group.
- RANK()Syntax example:
- sqlCopy codeSELECT
- employee_id,
- salary,
- RANK() OVER (ORDER BY salary DESC) AS salary_rank
- FROM employees;
复制代码 - Definition: Assigns a rank to each row within a partition, starting at 1. Rows with the same ordering value (ties) receive the same rank. Then, the next distinct value after a tie is assigned a rank that reflects the number of preceding rows.
- Behavior with ties: If two rows are tied for first place, both get RANK = 1, but the next unique value after these two tied rows would get RANK = 3 (not 2, because two rows came before it).
- Example use case:
- Ranking employees by salary, showing that employees with the same salary have the same rank, and skipping ranks after ties.
- DENSE_RANK()Syntax example:
- sqlCopy codeSELECT
- employee_id,
- salary,
- DENSE_RANK() OVER (ORDER BY salary DESC) AS dense_salary_rank
- FROM employees;
复制代码 - Definition: Similar to RANK(), except that after a tie, the next rank number increments by 1 rather than by the count of tied rows.
- Behavior with ties: If two rows are tied for first place, both get DENSE_RANK = 1, and the next distinct value after these two tied rows will get DENSE_RANK = 2 (instead of 3 as it would with RANK()).
- Example use case:
- When you want to assign consecutive rank values without gaps.
- NTILE(n)Syntax example:
- sqlCopy codeSELECT
- employee_id,
- salary,
- NTILE(4) OVER (ORDER BY salary DESC) AS salary_quartile
- FROM employees;
复制代码 - Definition: Distributes rows into a specified number of roughly equal groups and assigns a tile number (from 1 to n) to each row.
- Use case:
- Dividing your result set into buckets or quantiles (like quartiles or deciles).
Comparing the Behaviors
Imagine we have a result set of salaries, sorted in descending order, and the salaries are as follows:
Salary |
|---|
100000 |
100000 |
80000 |
60000 |
60000 |
60000 |
50000 |
ROW_NUMBER() OVER (ORDER BY Salary DESC):- Rows get unique numbers regardless of ties.
- Results:
- 100000 → 1
- 100000 → 2
- 80000 → 3
- 60000 → 4
- 60000 → 5
- 60000 → 6
- 50000 → 7
RANK() OVER (ORDER BY Salary DESC):- Ties get the same rank; the next rank is incremented by the number of previous rows.
- Results:
- 100000 → 1
- 100000 → 1
- 80000 → 3 (not 2, because two rows are tied for 1st)
- 60000 → 4
- 60000 → 4
- 60000 → 4
- 50000 → 7 (since six rows preceded it, even though some were tied)
DENSE_RANK() OVER (ORDER BY Salary DESC):- Ties get the same rank; the next rank increments by 1 regardless of how many were tied.
- Results:
- 100000 → 1
- 100000 → 1
- 80000 → 2 (instead of 3, since we don't "skip" any rank number)
- 60000 → 3
- 60000 → 3
- 60000 → 3
- 50000 → 4 (instead of 7 as with RANK())
Using PARTITION BY
All these functions can use aclause inside theclause to "reset" the ranking for each partition. For example, if you want to rank employees by salary within each department:- sqlCopy codeSELECT
- department_id,
- employee_id,
- salary,
- DENSE_RANK() OVER (PARTITION BY department_id ORDER BY salary DESC) AS dept_salary_rank
- FROM employees;
复制代码 In this scenario, the ranking restarts at 1 for each department.Practical Tips
- Choosing the right function:
- Use ROW_NUMBER() when you need a unique sequence and do not care about ties.
- Use RANK() when you want to reflect ties with identical ranks but keep the idea of how many rows came before.
- Use DENSE_RANK() when you want to reflect ties but don’t want gaps in the ranking numbers.
- Use NTILE() to split your data into N buckets for distribution analysis.
- Performance considerations:
- Ranking functions require anclause in thewindow. This ordering can affect performance on large datasets. Proper indexing and sometimes query rewrites can help.
- Integration with other clauses:
- Ranking functions appear in the SELECT list or in the ORDER BY clause of a query, but not typically in a WHERE clause. To filter based on ranks, you often use a subquery or a Common Table Expression (CTE).
Example with a CTE filtering top 3 salaries per department:- sqlCopy codeWITH ranked_salaries AS (
- SELECT
- department_id,
- employee_id,
- salary,
- DENSE_RANK() OVER (PARTITION BY department_id ORDER BY salary DESC) AS rnk
- FROM employees
- )
- SELECT *
- FROM ranked_salaries
- WHERE rnk <= 3;
复制代码 This returns the top 3 employees by salary for each department, handling ties gracefully.
补充内容 (2024-12-06 07:51 +08:00):
帮忙点个赞或者加个米感谢 |