Select EMP with max SAL from each DEPT

前端 未结 4 1273
予麋鹿
予麋鹿 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:21

    You can also use the analytical RANK() function:

    SELECT * FROM (
      SELECT
        Dept.DeptNo,
        Dept.DName,
        Emp.EName,
        Emp.Sal,
        RANK() OVER (PARTITION BY Dept.DeptNo ORDER BY Emp.Sal DESC) AS DeptSalRank
      FROM Emp
      INNER JOIN Dept ON Emp.DeptNo = Dept.DeptNo
    )
    WHERE DeptSalRank = 1
    
    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2021-01-25 23:36

    The following query will omit duplicate values

    SELECT DEPTNO, MAX(SAL) FROM EMP GROUP BY DEPTNO;
    

    The following query will include the duplicate values

    SELECT * FROM EMP WHERE (DEPTNO,SAL) IN 
    ( SELECT DEPTNO, MAX(SAL) FROM EMP GROUP BY DEPTNO)
    
    0 讨论(0)
  • 2021-01-25 23:36

    As short as the question: SELECT DeptID, MAX(Salary) FROM Employees GROUP BY DeptID

    0 讨论(0)
提交回复
热议问题