部门表 depart 
KeyId varchar(50) 
DepartName varchar(200) 
ParentId varchar(50) 数据: 
AA001 总经办 root 
AB001 事业部 root
AA002 行政部 AA001 
AB002 客服部 AB001 
AB003 研发部 AB001 
AB004 支持部 AB002 人数表 departTotal 
KeyId int 
DepartID varchar(50) 
Count int 数据: 
1 AA001 10 
2 AB001 10 
3 AA002 10 
4 AB002 10 
5 AB003 10 
6 AB004 10 求统计各部门的人数,结果如下: 
AA001 总经办 20 
AA002 行政部 10 
AB001 事业部 40 
AB002 客服部 20 
AB003 研发部 10 
AB004 支持部 10 多级部门统计

解决方案 »

  1.   

    2005(含)以上版本的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
    */