Dear Good people
I have table of employees and column called managedby. I want to roll actual and target figures up from employee to lead to manager to director and etc.
create table
(
empid int
,Name varchar(255)
,actual decimal(38,2)
,target decimal(38,2)
,managedby int
)
and below is what have done so far:
with emp(Period,Label,[name],Unit,Department,[Group],Division,Managed_By,Manager,Actual,Target) as
(
select
a.DW_Time_key Period
,Label
,b.name
,b.Unit
,b.Department
,b.[Group]
,b.Division
,b.Managed_By
,b.Manager
,sum(a.Actual) Actual
,sum(a.Budget) Target
from
KPI_EDW.dbo.Fact_ASO_SCORECARD a
,KPI_EDW.dbo.DIM_Employee b
where
a.DW_EMPLOYEE_KEY = b.DW_EMPLOYEE_KEY
and DW_KPI_KEY = 1008
and DW_Time_key = 200906
--and DW_Division_KEY = 1003
group by
a.DW_Time_key
,b.name
,b.Unit
,b.Department
,b.[Group]
,b.Division
,b.Managed_By
,b.Manager
,b.Label
)
,CTE (Label,[Name],[Manager], Managed_By,Actual,Target,[level]) as
(
select cast(Label as int) Label,[Name],[Manager], null,Actual,Target,0
from emp
where cast(Label as int) = '582'
union all
select
cast(h2.Label as int) Label
,h2.[Name]
,h2.[Manager]
,cast(h2.Managed_By as int) Managed_By
,h2.Actual
,h2.Target
,[level] + 1
from emp h2
inner join cte
on cast(h2.Managed_By as int) = cast(cte.Label as int)
)
select *
from cte
order by [level]
Thanks in advance