给你写个吧 要递归取出所有产品明细的。
--向下递归
with temp
as
(
select ID,PID,Name,cast(ID as varchar(max)) as fuid from cost
--where ID=‘01‘
union all
select a.ID, a.PID,a.Name, temp.fuid+'/'+cast(a.id as varchar(max)) as fuid from cost a
inner join temp on a.[PID] = temp.[ID]
)
--取产品展开明细
select a.*,b.Price, case when CHARINDEX('/',fuid)>0 then SUBSTRING(fuid,1,CHARINDEX('/',fuid)-1) else fuid end as topid
into #temp2
from temp a inner join price b on a.ID=b.id
--取所有产品的明细
select *
from cost a
left join #temp2 b on a.ID=b.topid
--取所有产品的合计
select a.name as 产品,sum(b.price) as 金额
from cost a
left join #temp2 b on a.ID=b.topid
group by a.name
drop table #temp2