简体   繁体   English

减去多行查询

[英]Subtracting multi-row queries

I'm trying to write a sql query to figure out by how much have salaries increased in the last year for each department due to new employees. 我正在尝试编写一个sql查询来找出由于新员工而导致每个部门的工资在去年增加了多少。

Table structure is Employees (empno, deptno, msal, hiredate) 表结构为员工(empno,deptno,msal,hiratedate)

I can figure out how to get all the salaries by departments 我可以弄清楚如何按部门索取全部工资

SELECT sum(msal) FROM employees GROUP BY deptno;

and how to get the salaries from people who were hired in the past year 以及如何从过去一年中雇用的人那里获得薪水

SELECT sum(msal) FROM employees WHERE hiredate > (DATEADD(year, -1, GETDATE())) GROUP BY deptno;

But whatever way I try to subtract the result of these two queries I only get errors. 但是无论我以什么方式尝试减去这两个查询的结果,我只会得到错误。

Here is what you might do. 这是您可能会做的。 In this case I'm using a CASE statement to filter new employees: 在这种情况下,我使用CASE语句来筛选新员工:

SELECT SUM(msal) - SUM(CASE WHEN hiredate > ADD_MONTHS(SYSDATE, -12) THEN msal ELSE 0 END)
  FROM employees
 GROUP BY deptno;

FYI, Oracle doesn't have a DATEADD() function nor does it have a GETDATE() function. 仅供参考,Oracle没有DATEADD()函数,也没有GETDATE()函数。 Note that I used ADD_MONTHS() and SYSDATE (you could also use CURRENT_DATE ) in place of these. 请注意,我使用了ADD_MONTHS()SYSDATE (也可以使用CURRENT_DATE )来代替它们。

Why not just change the direction of the where ? 为什么不改变方向where

SELECT sum(msal)
FROM employees
WHERE hiredate <= DATEADD(year, -1, GETDATE())
GROUP BY deptno;

Also, normally when you aggregate by a field, then the field ( deptno ) is included in the select clause. 同样,通常,当您按字段进行聚合时,该字段( deptno )会包含在select子句中。

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

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