select distinct id, pid into #temp1 from a where pid ='aa' and level=2
select distinct id, pid into #temp2 from a where pid in (select id from #temp1) and level=3
select distinct id, pid into #temp3 from a where pid in (select id from #temp2) and level=3
select id from #temp1
union
select id from #temp2
union
select id from #temp3