在oracle数据样本中,处理每组最低工资问题(当存在重复时)

in oracle data sample, Deal with Minimum salary problem per group(when duplicates exist)

雇员

empno   ename   job         mgr     hiredate    sal    comm   deptno
7369    SMITH   CLERK       7902    80/12/17    800     null   20
7499    ALLEN   SALESMAN    7698    81/02/20    1600    300    30
7521    WARD    SALESMAN    7698    81/02/22    1250    500    30
7566    JONES   MANAGER     7839    81/04/02    2975    null   20
7654    MARTIN  SALESMAN    7698    81/09/28    1250    1400   30
7698    BLAKE   MANAGER     7839    81/05/01    2850    null   30
7782    CLARK   MANAGER     7839    81/06/09    2450    null   10
7788    SCOTT   ANALYST     7566    82/12/09    3000    null   20
7839    KING    PRESIDENT   null    81/11/17    5000    null   10
7844    TURNER  SALESMAN    7698    81/09/08    1500    null   30
7876    ADAMS   CLERK       7788    83/01/12    1100    null   20
7900    JAMES   CLERK       7698    81/12/03    950     null   30
7902    FORD    ANALYST     7566    81/12/03    3000    null   20
7934    MILLER  CLERK       7782    82/01/23    1300    null   10

每位经理需要在其他员工中找到工资最低的员工。不过最低年薪1000多

我试过了

select e.ename, e.sal, e.mgr
from (select ename, sal, mgr from emp where sal > 1000) e
where (e.sal, mgr) in (select min(sal), mgr from emp group by mgr) and mgr is not null
order by sal desc;

这是结果

ename   sal     mgr
SCOTT   3000    7566
FORD    3000    7566
CLARK   2450    7839
MILLER  1300    7782
ADAMS   1100    7788

大家可以看到,7698个manager的employee中,salary必须超过1000,而min小于1000,所以用我的代码执行时排除了。

结果如我所愿

ename   sal     mgr
SCOTT   3000    7566
FORD    3000    7566
CLARK   2450    7839
MILLER  1300    7782
WARD    1250    7698
MARTIN  1250    7698
ADAMS   1100    7788

我希望最终输出值按照薪水降序排列

我应该在代码中更改什么?

*在我的 oracle 版本中 -> oracle 11g

select ename, sal, mgr from emp 
where (sal, mgr) in (
  select min(case when sal >= 1000 then sal end), mgr 
  from emp group by mgr
) 
and mgr is not null
order by sal desc;

MIN() 聚合函数可以接受 CASE 表达式。在这里,我们要取消任何小于 1000 的值。MIN() 将 return 一个最小的 NON-NULL 值,只要对于给定的组至少有一个值是 1000 或以上。

您还可以执行以下操作,MIN() 解析函数。

select * from (
  select emp.*, min(case when sal >= 1000 then sal end) over (partition by mgr) mn 
  from emp
)
where mgr is not null and sal = mn
order by sal desc;