I have employees table with columns name, salary and department. I need to impute the NULL values in the salary column with average salary value in their corresponding department. How to do it in SQL?
Suppose if a particular employee salary value is NULL and that employee belongs to X dept. The code should replace the NULL value in the salary column with the 'average salary of employees in X dept'
Table:
----------------------------
Name | Salary | Department |
----------------------------
Abhi | 30,000 | Physics |
Suri | 50,000 | Geology |
Ajay | 70,000 | Physics |
Anu | 30,000 | Physics |
Ajit | 25,000 | Geology |
Banu | 20,000 | Electronics|
Sanju| 15,000 | Electronics|
Taman|NULL | Physics |
Now Taman's salary is NULL and he belongs to Physics department. We need to replace the NULL value with the average salary in Physics department, that is 43,333.3 The average in Physics dept is taken as (30K + 70K + 30K)/3.
Result:
----------------------------
Name | Salary | Department |
----------------------------
Abhi | 30,000 | Physics |
Suri | 50,000 | Geology |
Ajay | 70,000 | Physics |
Anu | 30,000 | Physics |
Ajit | 25,000 | Geology |
Banu | 20,000 | Electronics|
Sanju| 15,000 | Electronics|
Taman|43.333.3| Physics |