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
select
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