Select EMP with max SAL from each DEPT

前端 未结 4 1280
予麋鹿
予麋鹿 2021-01-25 22:38

I´m having a bad time with a SQL query. I´m using oracle default tables:

\'EMP\' TABLE

http://imageshack.us/photo/my-images/850/sinttuloxps.png/

AND

4条回答
  •  南笙
    南笙 (楼主)
    2021-01-25 23:34

    Classic greatest-n-per-group query. Here is what you want:

    select dept.dname, emp.empno, emp.ename, emp.sal
    from emp
    inner join dept on emp.deptno = dept.deptno
    inner join
    (
    select emp.deptno, max(emp.sal) sal
    from emp
    group by emp.deptno
    ) ss on emp.deptno = ss.deptno and emp.sal = ss.sal
    order by emp.sal desc
    

    Here is a working fiddle: http://sqlfiddle.com/#!4/7147b/6

    Additionally, you might want to checkout a different approach. Look here (SQL Select only rows with Max Value on a Column) to see an interesting answer on the topic.

提交回复
热议问题