日期:2014-05-17  浏览次数:20897 次

产品BOM结构的递归查询,查询到最底层物料
数据表中数据如下:

父级   子级   用量
A      B     1
B      C     2
C      D     1
B1     C1    1
X      B     2
X      B1    2

希望得到以下结果:
顶层   子层  用量    标识 
A      B     1
A      C     2
A      D     2    底层
X      B     2
X      B1    2
X      C1    2    底层
X      C     4
X      D     4    底层

谢谢各位大侠!

------解决方案--------------------

create table sx
(父级 varchar(5),子级 varchar(5),用量 int)

insert into sx
 select 'A','B',1 union all
 select 'B','C',2 union all
 select 'C','D',1 union all
 select 'B1','C1',1 union all
 select 'X','B',2 union all
 select 'X','B1',2


with t as
(select a.父级 '顶层',a.子级,a.用量
  from sx a
  where not exists(select 1 from sx b where b.子级=a.父级)
 union all
 select d.顶层,c.子级,c.用量*d.用量
  from sx c
  inner join t d on c.父级=d.子级
)
select a.顶层,a.子级,a.用量,
       case when not exists(select 1 from sx b where b.父级=a.子级)
            then '底层' else '' end '标识'
 from t a
 order by a.顶层

/*
顶层    子级    用量       标识
----- ----- ----------- ----
A     B      1           
A     C      2           
A