查看: 772| 回复: 0
跳转到指定楼层
上一主题 下一主题
收起左侧

SQL的几个rank需要搞清楚

全局:

注册一亩三分地论坛,查看更多干货!

您需要 登录 才可以下载或查看附件。没有帐号?注册账号

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:
    1. sqlCopy codeSELECT
    2.     employee_id,
    3.     salary,
    4.     ROW_NUMBER() OVER (ORDER BY salary DESC) AS row_num
    5. 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:
    1. sqlCopy codeSELECT
    2.     employee_id,
    3.     salary,
    4.     RANK() OVER (ORDER BY salary DESC) AS salary_rank
    5. 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:
    1. sqlCopy codeSELECT
    2.     employee_id,
    3.     salary,
    4.     DENSE_RANK() OVER (ORDER BY salary DESC) AS dense_salary_rank
    5. 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:
    1. sqlCopy codeSELECT
    2.     employee_id,
    3.     salary,
    4.     NTILE(4) OVER (ORDER BY salary DESC) AS salary_quartile
    5. 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 a
  1. PARTITION BY
复制代码
clause inside the
  1. OVER()
复制代码
clause to "reset" the ranking for each partition. For example, if you want to rank employees by salary within each department:
  1. sqlCopy codeSELECT
  2.     department_id,
  3.     employee_id,
  4.     salary,
  5.     DENSE_RANK() OVER (PARTITION BY department_id ORDER BY salary DESC) AS dept_salary_rank
  6. 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 an
      1. ORDER BY
      复制代码
      clause in the
      1. OVER()
      复制代码
      window. 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:
  1. sqlCopy codeWITH ranked_salaries AS (
  2.     SELECT
  3.         department_id,
  4.         employee_id,
  5.         salary,
  6.         DENSE_RANK() OVER (PARTITION BY department_id ORDER BY salary DESC) AS rnk
  7.     FROM employees
  8. )
  9. SELECT *
  10. FROM ranked_salaries
  11. WHERE rnk <= 3;
复制代码
This returns the top 3 employees by salary for each department, handling ties gracefully.

补充内容 (2024-12-06 07:51 +08:00):

帮忙点个赞或者加个米感谢

上一篇:请教python 做工程项目的建议
下一篇:heatmap 有标准答案吗
您需要登录后才可以回帖 登录 | 注册账号
隐私提醒:
  • ☑ 禁止发布广告,拉群,贴个人联系方式:找人请去🔗同学同事飞友,拉群请去🔗拉群结伴,广告请去🔗跳蚤市场,和 🔗租房广告|找室友
  • ☑ 论坛内容在发帖 30 分钟内可以编辑,过后则不能删帖。为防止被骚扰甚至人肉,不要公开留微信等联系方式,如有需求请以论坛私信方式发送。
  • ☑ 干货版块可免费使用 🔗超级匿名:面经(美国面经、中国面经、数科面经、PM面经),抖包袱(美国、中国)和录取汇报、定位选校版
  • ☑ 查阅全站 🔗各种匿名方法

本版积分规则

>
快速回复 返回顶部 返回列表