Search code examples
sqlnestedsumdb2having

DB2 SQL Having Clause with a Nested Table Expression


Return the department number and the total payroll for the department that has the highest payroll. Payroll is the sum of all salaries and commissions of the department. Use a having clause with a nested table expression.

select e0.deptno,
(select sum(sal+com) FROM emp  
group by deptno
having sum(sal+com) >= all(select sum(sal+com) 
                       from emp
                       group by deptno) )as top
from emp as e0
group by e0.deptno
;

But my result is not correct. Im not so sure if my nested table expression combined with the having clause is done the right way. Can someone, try to help me? Thanks in advance.


Solution

  • As far as concerned, you don't need a having clause for this. You can just aggregate by department, order the results by payroll and fetch the first record:

    select deptno, sum(sal + com) payroll
    from emp e
    group by deptno
    order by payroll desc
    fetch first 1 rows only
    

    If you do want to use having (or if you are using a version of db2 that does not support the fetch ... rows ... clause), then we can build on your initial idea as follows:

    select deptno, sum(sal + com) payroll
    from emp
    group by deptno
    having sum(sal + com) >= all (
        select sum(sal + com) from emp group by deptno
    )