⚠️⚠️⚠️

1. rank()和dense_rank()区别

2. rank(),dense_rank()括号里不加列名,在order by 后面加要排名的列

3. where, group by, having都不能直接引用window function,但order by 可以引用。因为select的执行顺序在where, group by, having之后,但在order by 之前

解决办法:
1. 先把包含 window function的语句, 建立成表
2.放到from 后面的子查询表,一个道理 先建立成表,再引用select里面的窗口函数

区别RANK,DENSE_RANK和ROW_NUMBER

  • RANK并列跳跃排名,并列即相同的值,相同的值保留重复名次,遇到下一个不同值时,跳跃到总共的排名。
  • DENSE_RANK并列连续排序,并列即相同的值,相同的值保留重复名次,遇到下一个不同值时,依然按照连续数字排名。
  • ROW_NUMBER连续排名,即使相同的值,依旧按照连续数字进行排名。

区别如图:
[Hard] Department Top Three Salaries - 图1

题目

The Employee table holds all employees. Every employee has an Id, and there is also a column for the department Id.
Screen Shot 2020-11-05 at 7.07.08 PM.png

The Department table holds all departments of the company.
Screen Shot 2020-11-05 at 7.08.27 PM.png
Write a SQL query to find employees who earn the top three salaries in each of the department. For the above tables, your SQL query should return the following rows (order of rows does not matter).

Screen Shot 2020-11-05 at 7.07.50 PM.png

答案

方式1:先把包含 window function的语句, 建立成表

Screen Shot 2020-11-05 at 7.09.07 PM.png
**

方式2:放到from 后面的子查询表,一个道理 先建立成表,再引用select里面的窗口函数

Screen Shot 2020-11-05 at 7.09.29 PM.png