Below is the Employee
table which includes manager details as well. The task is to calculate the average salary under manager:
emp_id emp_name salary manager_id
----------- -------- --------- -------------
10 Anil 50000.00 18
11 Vikas 75000.00 16
12 Nisha 40000.00 18
13 Nidhi 60000.00 17
14 Priya 80000.00 18
15 Mohit 45000.00 18
16 Rajesh 90000.00 NULL
17 Raman 55000.00 16
18 Santosh 65000.00 17
I have written below query:
SELECT e1.emp_id as manager_id,
e1.emp_name as manager_name,
avg(e2.salary) as employee_avg_salary
FROM employee e1 inner join
employee e2
ON e1.manager_id = e2.emp_id
GROUP BY e1.emp_id, e1.emp_name
ORDER BY e1.emp_id
which is wrong as per solution set.
My thinking was I'm doing self-join on the employee table on condition manager_id from e1 is equal to employee id from e2 so grouped by e1.emp_id and e1.emp_name since left side contains manager set.
The current solution seems to be
select e2.emp_id as "Manager_Id",
e2.emp_name as "Manager",
avg(a.salary) as "Average_Salary_Under_Manager"
from Employee e1,
Employee e2
where e1.manager_id = e2.emp_id
group by e2.emp_id, e2.emp_name
order by e2.emp_id;
The result set should be
ManagerId ManagerName AverageSalary
-----------------------------------------
16 Rajesh 65000
17 Raman 62500
18 Santosh 53750
(3 rows affected)
Could somebody please explain the logic why is it so, I'm asking only for the explanation.