Oracle SQL查找组中的前N行

时间:2015-03-30 14:26:02

标签: sql oracle greatest-n-per-group

我正在尝试查询行的前N个,但在OracleSQL内部有一个组

例如:

+-----+----------+----+------+
|JobID|JobTitle  |Pay |Name  |
+-----+----------+----+------+
|012  |Manager   |400 |Bob   |
|012  |Manager   |400 |Gemma |
|012  |Manager   |400 |Ash   |
|020  |Supervisor|400 |Dan   |
|020  |Supervisor|400 |Hannah|
|013  |Clerk     |300 |Sarah |
+-----+----------+----+------+

从上面的例子中我想找到一份职位名下的所有员工,然后只显示前三名最有薪职位,然后按薪酬排序。

+-----+----------+----+------+
|JobID|JobTitle  |Pay |Name  |
+-----+----------+----+------+
|02   |Manager   |400 |Bob   |
|02   |Manager   |400 |Gemma |
|02   |Manager   |400 |Ash   |
|04   |Supervisor|400 |Dan   |
|04   |Supervisor|400 |Hannah|
|03   |Clerk     |300 |Sarah |
|01   |Cleaner   |200 |Scruff|
|01   |Cleaner   |200 |Fry   |
+-----+----------+----+------+

会是桌子。

我尝试过使用子查询,然后添加rownum< = 3;最后,但仍然无法找到理想的结果。

    SELECT * FROM 
      ( SELECT JobID, MAX(Pay) AS Pay, JobTitle, EmpID, Name 
        FROM Employees,Jobs
        WHERE JobID = Employees.Job_ID
        GROUP BY JobID, Pay, EmpID, JobTitle,
        ORDER BY Pay DESC)
     WHERE ROWNUM <= 3;

1 个答案:

答案 0 :(得分:2)

最好使用窗口功能:

select jobid, jobtitle, pay, name
from (
  select j.jobid, j.jobtitle, e.pay, e.name, 
         row_number() over (partition by j.jobid order by e.pay desc) as rn
  from employees e 
    join jobs j on j.jobid = e.job_id
) 
where rn <= 3
order by jobid, jobtitle, pay desc;

我还将where子句中过时的隐式连接更改为显式JOIN