当前位置: 代码迷 >> Sql Server >> CTE有关问题:BOM从底层找到最顶层的记录
  详细解决方案

CTE有关问题:BOM从底层找到最顶层的记录

热度:98   发布时间:2016-04-24 10:17:33.0
CTE问题:BOM从底层找到最顶层的记录
我有数据如下:
Item Parent
RE4 S10
S10         S20
S20         S30
S20         F10
S30         F20

如何由底层代码 RE4:
1. 找到其所有物料
2. 列出最顶层的物料

多尝试:
;with cet(level, item, parent)
as (
select 0 as level, item, parent from item where item = 'RE4'
union all
select cet.level + 1, item, partent 
from item inner join cet on cet.parent = item.item
)
select * from cet


但都只能列出其所有物料,因为S20用于多个父物料下面,所以,无法区分最顶层的物料来。 求教。
------解决方案--------------------
use tempdb
go

if not object_ID('Tempdb..#1') is null
drop table #1
Go
Create table #1([Item] nvarchar(3),[Parent] nvarchar(3))
Insert #1
select 'RE4','S10' union all
select 'S10','S20' union all
select 'S20','S30' union all
select 'S20','F10' union all
select 'S30','F20'
Go
;with cte_test as 
(
select * from #1 a where a.Item='RE4'
union all 
select a.*
from #1 a
inner join cte_test b on b.Parent=a.Item
)
Select * from cte_test a where not exists(select 1 from #1 x where x.Item=a.Parent)
/*
Item Parent
------------------
S20 F10
S30 F20
*/


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

create table #t
(Item varchar(10),Parent varchar(10))

insert into #t
 select 'RE4','S10' union all
 select 'S10','S20' union all
 select 'S20','S30' union all
 select 'S20','F10' union all
 select 'S30','F20'
 

declare @x varchar(10)
select @x='RE4'

;with u as
(select *,1 'lv' from #t where Item=@x
 union all
 select a.*,b.lv+1 'lv'
  from #t a
  inner join u b on a.Item=b.Parent)
select c.Parent 
 from u c
 where not exists(select 1 
                  from u d 
                  where d.Item=c.Parent)

/*
Parent
----------
F10
F20

(2 row(s) affected)
*/
  相关解决方案