返回每个部门ID最高工资的员工姓名和工资

时间:2013-11-18 18:34:27

标签: sql oracle

emp_tbl

========================================
emp_id  ename       sal dept_id
========================================
1001    rajesh      10000   10
1002    ashish      18000   10
1003    ravi        9000    20
1004    raj     8500    20
1005    rajan       11000   30
1006    ashok       7000    30

是否有人可以帮我编写一个SQL查询,以便为该部门中拥有最高薪水的每个ename获取saldept_id

3 个答案:

答案 0 :(得分:1)

重复this个问题

SELECT DISTINCT
       MAX( ename ) KEEP ( DENSE_RANK LAST ORDER BY sal ASC ) OVER ( PARTITION BY dept_id ) AS ename,
       MAX( sal   ) KEEP ( DENSE_RANK LAST ORDER BY sal ASC ) OVER ( PARTITION BY dept_id ) AS sal,
       dept_id
FROM   emp_tbl;

SQLFIDDLE

答案 1 :(得分:0)

这样的事情应该有效:

select t1.* from emp_tbl t1
join (
  select dept_id, max(sal) maxSal from emp_tbl
  group by dept_id
) t2
on t1.dept_id = t2.dept_id and t1.sal = t2.maxSal

或者,有左连接方法:

select t1.* from emp_tbl t1
left join emp_tbl t2 on t1.dept_id = t2.deptid and t1.sal < t2.sal
where t2.sal is null

答案 2 :(得分:0)

使用每个部门最大sal的派生表分组,我会使用dept_id和sal将其加入emp_tbl,以获得每个部门拥有最大sal的员工。

select 
    et.ename,
    et.sal
from 
    emp_tbl et,
    (select 
         dept_id,
         max(sal)
     from 
         emp_tbl
     group by 
         dept_id) max_sal_dept
where
    et.dept_id = max_sal_dept.dept_id
    and et.sal = max_sal_dept.sal