问题
Consider the table employee
:
desc employee;
Name Null? Type
-------------------------- -------- ------------
EMPLOYEENO NOT NULL NUMBER(4)
ENAME VARCHAR2(15)
JOB VARCHAR2(15)
MGR NUMBER(4)
HIREDATE DATE
SAL NUMBER
COMM NUMBER
DEPTNO NUMBER(2)
Contains with values of deptno
,sal
as:
DEPTNO SAL
---------- ----------
10 2450
10 5000
10 1300
20 2975
20 3000
20 1100
20 800
20 3000
30 1250
30 1500
30 1600
30 950
30 2850
30 1250
Need to update the salary of employees with their department's average salary. i.e set every employee's salary to the departmental average.Is there any solution possible with the group by clause something like
update employee set sal =(select avg(sal) from employee group by deptno) where deptno in(select deptno from employee group by deptno)
So how to query the same.
回答1:
Try this
UPDATE EMPLOYEE A
SET SAL = (SELECT AVG(SAL) FROM EMPLOYEE B WHERE B.DEPTNO = A.DEPTNO);
回答2:
update employee a
set sal = (select avg(sal) as avgsal
from employee b
where A.DEPTNO = b.deptno
);
回答3:
This would be much more efficiently implemented as a MERGE, in which the USING clause aggregates salaries for all departments to the department level and joins to the employee table on department_id.
来源:https://stackoverflow.com/questions/14544971/sql-to-update-the-salary-of-employees-with-their-departments-average-salary