This is my data ,
employee_id | name | manager_id | salary |
---|---|---|---|
1 | Alice | 100000.00 | |
2 | Bob | 1 | 80000.00 |
3 | Charlie | 1 | 75000.00 |
4 | David | 2 | 60000.00 |
5 | Eve | 2 | 50000.00 |
6 | Frank | 3 | 55000.00 |
Question is The total salary paid under each employee (including their own salary and all the salaries of their subordinates, directly or indirectly).
I tried hierarchical way and achieved below result.
employee_id | name | manager_id | salary | path | total_salary |
---|---|---|---|---|---|
1 | Alice | 100000.00 | boss | 100000 | |
2 | Bob | 1 | 80000.00 | boss->Bob | 180000 |
3 | Charlie | 1 | 75000.00 | boss->Charlie | 175000 |
4 | David | 2 | 60000.00 | boss->Bob->David | 240000 |
5 | Eve | 2 | 50000.00 | boss->Bob->Eve | 230000 |
6 | Frank | 3 | 55000.00 | boss->Charlie->Frank | 230000 |
but my expectation is for Alice should be 430000.00,Bob ->190000.00,Charlie ->
employee_id | name | manager_id | salary | path | total_salary |
---|---|---|---|---|---|
1 | Alice | NULL | 100000.00 | boss | 430000.00 |
2 | Bob | 1 | 80000.00 | boss->Bob | 190000.00 |
3 | Charlie | 1 | 75000.00 | boss->Charlie | 130000.00 |
4 | David | 2 | 60000.00 | boss->Bob->David | 60000.00 |
5 | Eve | 2 | 50000.00 | boss->Bob->Eve | 50000.00 |
6 | Frank | 3 | 55000.00 | boss->Charlie->Frank | 55000.00 |
2
Answers
This can be done with a recursive cte to find all the subordinates for each person in the employee table and then their salaries merely need to be summed to calculate the total salary.
There we save root id for employee and join other rows of hierarchy tree in recursion.
We get (for Alice) Alice as child of level 1, Charlie and Bob as childs of level 2…
See example
fiddle
Minimize query, excluding code part for debugging and clarity
If you want get all columns from your table and only add totals column