在oracle数据示例中,处理每个组的最低工资问题(当存在重复时)



emp

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名经理的员工中,工资必须超过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的值无效。只要给定组至少有一个1000或以上的值,MIN((就会返回最小的NON-NULL值。

您也可以执行以下,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;

最新更新