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.
Table structure is Employees (empno, deptno, msal, hiredate)
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:
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. Note that I used ADD_MONTHS()
and SYSDATE
(you could also use CURRENT_DATE
) in place of these.
Why not just change the direction of the 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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.