create table #t (id int,fid int,name varchar(10))
insert into #t
select 1, 0,'A'  union all
select 2,0 ,'B' union all
select 3, 0,'C' union all
select 4, 0, 'D' union all
select 5, 1, 'A1' union all
select 6, 1, 'A2' union all
select 7,  2,'B1' union all
select 8, 2, 'B2' union all
select 9, 2,'B3' select name+'('+cast(sum(case when fid>0 then 1 else 0 end) as varchar(10))+')'
from (
select name=a.name,fid=b.fid
from
(select id,fid,name from #t where fid=0 )a left join #t b on  a.id=b.fid
)c
group by name