简体   繁体   English

具有嵌套表表达式的 DB2 SQL 子句

[英]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.使用带有嵌套表表达式的 having 子句。

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.我不太确定我的嵌套表表达式与 have 子句结合是否以正确的方式完成。 Can someone, try to help me?有人可以尝试帮助我吗? Thanks in advance.提前致谢。

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:如果您确实想要使用having (或者如果您使用的是不支持fetch ... rows ...子句的 db2 版本),那么我们可以在您最初的想法的基础上构建如下:

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
)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM