如何使用 BREAK 和 COMPUTE SUM 对 deptno ( deptno 10,20,30) 上 table EMP 的两个最高薪水求和?

How to SUM two highest salary on table EMP on deptno ( deptno 10,20,30) using BREAK and COMPUTE SUM?

这是我的代码:

BREAK ON DEPTNO SKIP 1
compute sum of sal on deptno
SELECT  deptno, empno, ename,sal FROM
(SELECT  deptno, empno, ename, sal FROM emp group by deptno, empno, ename, sal  order by DEPTNO)
  WHERE   ROWNUM <= 2;

但结果是:

    DEPTNO      EMPNO ENAME             SAL
---------- ---------- ---------- ----------
        10       7782 CLARK            2450
                 7839 KING             5000
**********                       ----------
sum                                    7450

很好,但我还想在 deptno 20、deptno 30 上获得: (这是预期结果,全部相同 return - 对于 deptno 10、20,30)

    DEPTNO      EMPNO ENAME             SAL
---------- ---------- ---------- ----------
        10       7782 CLARK            2450
                 7839 KING             5000
**********                       ----------
sum                                    7450

    DEPTNO      EMPNO ENAME             SAL
---------- ---------- ---------- ----------
        20       7788 SCOTT            3000
                 7902 FORD             3000
                 7566 JONES            2975
**********                       ----------
sum                                    8975

    DEPTNO      EMPNO ENAME                SAL
---------- ---------- ---------- ----------
        30       7698 BLAKE            2850
                 7499 ALLEN            1600
**********                       ----------
sum                                    4450

我的问题是如何使用 BREAKCOMPUTE SUM 将 deptno (deptno 10,20,30) 上 table EMP 的两个最高薪水相加 return(就像上面预期的那样)?

我认为我的代码非常好,但缺少一些东西。

很抱歉,您的查询没有多大意义。你从 emp 中 select 并按 empno(和其他列)分组,所以你说:"Give me data from emp, but make it one record per empno",这意味着根本没有分组(因为 emp 中每个 empno 恰好有一个记录)。

你的子查询

SELECT deptno, empno, ename, sal 
FROM emp
group by deptno, empno, ename, sal 
order by DEPTNO

相同
SELECT deptno, empno, ename, sal 
FROM emp
order by DEPTNO

然后在按 deptno 排序记录后取前两行,因此您会为第一个 deptno 任意选择两个 emp 记录。

你想要的是显示 emp 记录(即没有分组依据)每个部门的两个最高薪水。您可以使用分析函数 DENSE_RANK 对每个部门的薪水进行排名。然后留在排名1和2的记录。

select deptno, empno, ename, sal
from
(
  select 
    deptno, empno, ename, sal,
    dense_rank() over (partition by deptno order by sal desc) as rnk
  from emp 
)
where rnk <= 2
order by deptno, sal desc;