日期:2014-05-17 浏览次数:20637 次
use tempdb
declare @depart table(KeyId varchar(50),DepartName varchar(200) ,ParentId varchar(50) )
declare @departTotal table(KeyId int,DepartID varchar(50),Count int)
insert into @depart
select 'AA001', '总经办', 'root'
union all select 'AB001', '事业部', 'root'
union all select 'AA002', '行政部', 'AA001'
union all select 'AB002', '客服部', 'AB001'
union all select 'AB003', '研发部', 'AB001'
union all select 'AB004', '支持部', 'AB002'
insert @departTotal
select 1, 'AA001', 10
union all select 2, 'AB001', 10
union all select 3, 'AA002', 10
union all select 4, 'AB002', 10
union all select 5, 'AB003', 10
union all select 6, 'AB004', 10
--以下执行
;
with result as
(
select *,KeyId x from @depart
union all
select a.*,b.x from @depart as a join result as b on a.KeyId=b.ParentId
)
select a.KeyId,a.DepartName,SUM(b.Count) from result as a join @departTotal as b on a.x=b.DepartID
group by a.KeyId,a.DepartName
/*
AA001 总经办 20
AA002 行政部 10
AB001 事业部 40
AB002 客服部 20
AB003 研发部 10
AB004 支持部 10
*/