--try itselect  
t2.id,
t2.departmentname,
(select  sum(tt2.countperson) from  table2 tt2 
where tt2.id=t2.id or tt2.id in (select t1.id from table1 t1 where t1.topid=t2.id )
) as   total
from table2 t2

解决方案 »

  1.   

    create table #table1(ID int,TOPID int)
    insert #table1 values(1,     2)
    insert #table1 values(2 ,    0)
    insert #table1 values(3   ,  2)
    insert #table1 values(4  ,   3)
    insert #table1 values(5    , 3)
    create table #table2(id int,countperson int,departmentname varchar(100))
    insert #table2 values(1,     22    ,         '****')
    insert #table2 values(2 ,    11   ,           '**')
    insert #table2 values(3  ,   55  ,           '***')
    insert #table2 values(4   ,  545,              '**')
    insert #table2 values(5    , 44,             '**')select *,null 人数 into #result from #table2declare @tmp1 table (Id int,pid int)while exists(select 1 from #result where 人数 is null)
    begin  insert @tmp1 select * from #table1 where ID=(select min(id) from #result where 人数 is null)  while exists(select 1 from #table1 where topID in (select id from @tmp1) and id not in (select id from @tmp1))
        insert @tmp1 select * from #table1 where TOPID in (select id from @tmp1) and id not in (select id from @tmp1)  update #result set 人数=(select sum(countperson) from #table2 where id in (select id from @tmp1)) where id=(select min(id) from #result where 人数 is null)
      delete @tmp1
    end
    select * from #result
    go
    drop table #table1,#table2,#result--注意 #table1,#table2 分别为你的表,#result是结果临时表                                                    (SQLServer MVP 大力)
      

  2.   

    http://expert.csdn.net/Expert/topic/1375/1375432.xml?temp=.8570978