Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
181 views
in Technique[技术] by (71.8m points)

oracle - SQL to update the salary of employees with their department's average salary

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Try this

UPDATE EMPLOYEE A
SET SAL = (SELECT AVG(SAL) FROM EMPLOYEE B WHERE B.DEPTNO = A.DEPTNO);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...