@H_404_4@作用(Purpose)
@H_404_4@用来统计top-n或者bottom-n
比如你可以用它来统计(或者说查询)出
a.@H_404_4@各个部门工资@H_404_4@最高的@H_404_4@前 n个员工
b.@H_404_4@各个部门最先入职的@H_404_4@前 n个员工
所以符合这个应用情景条件是:
a.1对多(部门对员工)
b.要对多的一方(员工)最高或最低的某个字段(工资,入职时间等)进行统计
c.前n个@H_404_4@语法(Syntax)
ROW_NUMBER() over(PARTITION BY **A** ORDER BY **B** desc/asc)
其中:
A: 1对多中1的那一方
B: 最高或最低的某个字段@H_404_4@具体实例(Examples)
@H_404_4@各个部门工资@H_404_4@最高的@H_404_4@前 3个员工
SELECT department_id,first_name,last_name,salary FROM ( SELECT department_id,salary,ROW_NUMBER() OVER (PARTITION BY department_id ORDER BY salary desc) rn FROM HR.employees ) WHERE rn <= 3 ORDER BY department_id,salary DESC,last_name;
@H_404_4@各个部门最先入职的@H_404_4@前 3个员工
SELECT department_id,HIRE_DATE,ROW_NUMBER() OVER (PARTITION BY DEPARTMENT_ID ORDER BY HIRE_DATE ASC) R FROM HR.employees ) WHERE R <=3 ORDER BY department_id,HIRE_DATE ASC,last_name;