产品BOM结构的递归查询,查询到最底层物料

shixin333 2014-01-09 06:08:01
数据表中数据如下:

父级 子级 用量
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 底层

谢谢各位大侠!
...全文
677 8 打赏 收藏 转发到动态 举报
写回复
用AI写文章
8 条回复
切换为时间正序
请发表友善的回复…
发表回复
qq_35620544 2016-07-16
  • 打赏
  • 举报
回复
@唐诗三百首 我在orcle11 G 中运行code 报错,请问下这个是什么原因?
shixin333 2014-01-09
  • 打赏
  • 举报
回复
SQL 2000没有CTE 在SQL 2008中测试OK,谢谢 @唐诗三百首
唐诗三百首 2014-01-09
  • 打赏
  • 举报
回复
引用 5 楼 shixin333 的回复:
加了分号还是错误
在SQL2008R2,SQL2005环境测试正常,难道LZ环境是SQL2000?
shixin333 2014-01-09
  • 打赏
  • 举报
回复
加了分号还是错误
唐诗三百首 2014-01-09
  • 打赏
  • 举报
回复
try this,

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.顶层;
shoppo0505 2014-01-09
  • 打赏
  • 举报
回复
引用 2 楼 shixin333 的回复:
怎么执行SQL提示错误 消息 102,级别15,状态1,第12行 't' 附近有语法错误
with 前面加个分号 ; 试试
shixin333 2014-01-09
  • 打赏
  • 举报
回复
怎么执行SQL提示错误 消息 102,级别15,状态1,第12行 't' 附近有语法错误
唐诗三百首 2014-01-09
  • 打赏
  • 举报
回复

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     D      2           底层
X     B      2           
X     B1     2           
X     C1     2           底层
X     C      4           
X     D      4           底层

(8 row(s) affected)
*/

22,210

社区成员

发帖
与我相关
我的任务
社区描述
MS-SQL Server 疑难问题
社区管理员
  • 疑难问题社区
  • 尘觉
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧