declare @podr table(id int, pid int, name varchar(30))
insert into @podr(id, pid, name)
select 151, 330, 'Приморская ГРЭС' union all
select 152, 151, 'ЦТП' union all
select 326, 330, 'РУ' union all
select 327, 326, 'ГКР' union all
select 328, 151, 'ПРП' union all
select 329, 327, 'Участок №1' union all
select 330, 0, 'ЛуТЭК' union all
select 331, 327, 'Участок №2'
declare @data table(id int, podr_id int, kolvo int)
insert into @data(id, podr_id, kolvo)
select 1, 152, 7 union all
select 2, 328, 1 union all
select 3, 329, 4 union all
select 4, 331, 5
;with cte as (
select p.id, p.pid, d.kolvo
from @podr as p
join @data as d on d.podr_id = p.id
where not exists (select 1 from @podr as p1 where p1.pid = p.id
) -- на всякий случай, хотя должно хватить join
union all
select p.id, p.pid, c.kolvo
from @podr as p
join cte as c on c.pid = p.id
)
select p.*, c.kolvo
from @podr as p
join (select id, sum(kolvo) as kolvo
from cte
group by id
) as c on c.id = p.id
id pid name kolvo
----------- ----------- ------------------------------ -----------
151 330 Приморская ГРЭС 8
152 151 ЦТП 7
326 330 РУ 9
327 326 ГКР 9
328 151 ПРП 1
329 327 Участок №1 4
330 0 ЛуТЭК 17
331 327 Участок №2 5
(8 row(s) affected)