Oracle Analytic function for min value in grouping

前端 未结 4 1430
遥遥无期
遥遥无期 2021-01-12 08:06

I\'m new to working with analytic functions.

DEPT EMP   SALARY
---- ----- ------
  10 MARY  100000
  10 JOHN  200000
  10 SCOTT 300000
  20 BOB   100000
  20 BET         


        
4条回答
  •  逝去的感伤
    2021-01-12 08:48

    I think you were pretty close with your original query. The following would run and do match your test case:

    SELECT dept, 
      MIN(emp) KEEP(DENSE_RANK FIRST ORDER BY salary, ROWID) AS emp,
      MIN(salary) KEEP (DENSE_RANK FIRST ORDER BY salary, ROWID) AS salary
    FROM mytable
    GROUP BY dept
    

    In contrast to the RANK() solutions, this one guarantees at most one row per department. But that hints at a problem: what happens in a department where there are two employees on the lowest salary? The RANK() solutions will return both employees -- more than one row for the department. This answer will pick one arbitrarily and make sure there's only one for the department.

提交回复
热议问题