Problem
I have two tables. employee
and salary
.
For the employee
table I have employee_id
and supervisor_id
.
employee_id | supervisor_id |
---|---|
0 | 5 |
1 | 5 |
2 | 5 |
3 | 6 |
4 | 6 |
5 | 7 |
6 | 8 |
7 | NULL |
8 | NULL |
For the salary
table I have amount
and employee_id
.
employee_id | amount |
---|---|
0 | 200 |
1 | 300 |
2 | 400 |
3 | 100 |
4 | 100 |
5 | 500 |
6 | 600 |
7 | 1000 |
8 | 1000 |
Question
For the supervisor with no supervisor (in my case employee id 7 and 8) I want to get the mean of sum of salary of all the employees that are working under them. So, for 7, it would be employee 5,2,1 and 0 and for employee 8 it would be 6,4 and 3.
I have tried using recursive cte but haven't been able to make much progress with it
WITH RECURSIVE supervisor_tree AS (
SELECT e.id, e.supervisor_id, (SELECT f.amount FROM salary f WHERE f.employee_id= e.id) AS amount
FROM employees e
WHERE e.supervisor_id IS NULL -- only top-level supervisors
UNION ALL
SELECT e.id, e.supervisor_id, COALESCE(f.weight, 0) AS weight
FROM employees e
INNER JOIN salary f ON e.id = f.employee_id
INNER JOIN supervisor_tree st ON e.supervisor_id = st.id
)
SELECT supervisor_id, weight
FROM supervisor_tree;