sql server
create table #BOM
(
ID int not null primary key,
PARENT VARCHAR(10),
TYPE1 VARCHAR(10),
SON VARCHAR(10),
TYPE2 VARCHAR(10),
QTY INT
)
insert into #BOM
values
(1,'FG1','FG','SEMI1','M',3),
(2,'FG2','FG','SEMI2','M',2),
(3,'FG1','FG','RAW1','P',2),
(4,'FG1','FG','RAW2','P',5),
(5,'FG2','FG','RAW3','P',6),
(6,'SEMI1','M','RAW3','P',2),
(7,'SEMI2','M','RAW4','P',3)
with cte(parent,type1,son,type2,qty,level,up) as
(
select parent,type1,son,type2,qty,1 as level,parent as up from #bom
union all
select h.parent,h.type1,c.son,c.type2,h.qty*c.qty as qty,c.level+1 as level,c.parent as up from #bom h
inner join cte c on h.son=c.parent
)
select * from cte where type1='FG'order by parent