Skip to content
Advertisement

Query to select the manager and total salary of employees under the manager

I need to write a query to select the manager and total salary of employees under the manager.

The salary of employees should roll up to Manager based on hierarchy. Mgrid references to empid in the same table.

Table : Employee

Output should be ManagerName and Salary

In the above example : M2 has M3, M4, M6 directly under him. Also M4 has M5 under him and M5 has M7 under him. So those employees also should be included in the total for M2.

I tried using recursive CTE but lost in rolling up the salary.

Any help is appreciated.

Query :

M4 is Wrong… The way I rolling up using hierarchy is not right. I couldn’t think of any other way,

Advertisement

Answer

The solution below assigns managers a salary of 0 as a start for the recursive sum of their employee salaries. This eliminates the need for a Hierarchy column, a second CTE cte_emp or a complex sum aggregation (Sum(Salary) Over (order by Hierchacy rows between 1 following and unbounded following))

Sample data

Solution

Result

Fiddle to see things in action with intermediate steps.

User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement