oracle SQL:按最小和最大总和获取DEPT

时间:2015-12-02 20:47:11

标签: sql oracle

我有2个工作子查询,用于检查所有部门(DEPTNO)中的最小和最大SUMS。表EMP和DEPT具有DEPTNO单元

(SELECT min(sum(e.SAL)) FROM EMP e GROUP by e.DEPTNO);
(SELECT max(sum(e.SAL)) FROM EMP e GROUP by e.DEPTNO);

如何检查最小和最大子查询的DEPTNO是什么? 我的代码是ERROR:

SELECT d.DEPTNO 
FROM DEPT d 
WHERE sum(e.SAL) = (SELECT max(sum(e.SAL)) FROM EMP e GROUP by d.DEPTNO);

3 个答案:

答案 0 :(得分:1)

如果您希望部门获得最高金额,可以使用rownumrow_number()

select ed.*
from (select e.deptno, sum(e.sal) as sums,
             row_number() over (order by sum(e.sal) desc) as seqnum
      from emp e
      group by e.deptno
     ) ed
where seqnum = 1;

在Oracle 12g +中,这也可以写成:

      select e.deptno, sum(e.sal) as sums,
             row_number() over (order by sum(e.sal) desc) as seqnum
      from emp e
      group by e.deptno
      order by sum(e.sal) desc
      fetch first 1 row only;

答案 1 :(得分:1)

这是使用cte

执行此操作的一种方法
with salsums as (select deptno, sum(sal) salsum from emp group by deptno)
, maxandmin as (select max(salsum) maxsal, min(salsum) minsal from salsums)
select deptno 
from salsums cross join maxandmin
where salsum = maxsal or salsum = minsal

答案 2 :(得分:0)

好的,这比起初看起来更难。这就是我最终让它发挥作用的方式,但我更喜欢@ vkp的答案。

with sums as
(
  SELECT DEPTNO, SUM(SAL) AS SSAL
  FROM EMP
  GROUP BY DEPTNO
), mm as
(
  SELECT DEPTNO, SSAL, MIN(SSAL) OVER () as MIN_SSAL, MAX(SSAL) OVER () as MAX_SSAL
  FROM SUMS
)
SELECT 'MIN', DEPTNO, SSAL FROM mm WHERE SSAL=MIN_SSAL
UNION ALL
SELECT 'MAX', DEPTNO, SSAL FROM mm WHERE SSAL=MAX_SSAL

http://sqlfiddle.com/#!6/410c8/8