问题如下。请大家帮忙看看
比如;
产品 组件
30012 2300
30012 2400
30012 1200
2300 1100
2300 2200
2200 1230
2400 2200
2400 2500
2400 1500
2500 1120
3200 2100
3200 1200
2100 1100
需要得到下面的,也就是 我要显示产品的所有非叶结点,及其上级结点
根 非叶结点 非叶结点的上级
30012 30012 0
30012 2300 30012
30012 2400 30012
30012 2200 2300
30012 2200 2400
30012 2500 2400 3200 3200 0
3200 2100 3200
比如;
产品 组件
30012 2300
30012 2400
30012 1200
2300 1100
2300 2200
2200 1230
2400 2200
2400 2500
2400 1500
2500 1120
3200 2100
3200 1200
2100 1100
需要得到下面的,也就是 我要显示产品的所有非叶结点,及其上级结点
根 非叶结点 非叶结点的上级
30012 30012 0
30012 2300 30012
30012 2400 30012
30012 2200 2300
30012 2200 2400
30012 2500 2400 3200 3200 0
3200 2100 3200
create table #t(产品 int,组件 int)--插入测试数据
insert #t(产品,组件)
select '30012','2300' union all
select '30012','2400' union all
select '30012','1200' union all
select '2300','1100' union all
select '2300','2200' union all
select '2200','1230' union all
select '2400','2200' union all
select '2400','2500' union all
select '2400','1500' union all
select '2500','1120' union all
select '3200','2100' union all
select '3200','1200' union all
select '2100','1100'
--求解过程
declare @level int set @level = 1
select *,产品 as 根,@level as level
into #tmp
from #t t where 产品 not in(select 组件 from #t)and exists(select 1 from #t where t.组件 = 产品)while @@rowcount > 0
begin
set @level = @level + 1 insert #tmp
select t.产品,t.组件,_t.产品,@level
from #t t
join #tmp _t on _t.组件 = t.产品
where _t.level = @level - 1 and exists(select 1 from #t where t.组件 = 产品)
endselect 根,组件 as 非叶结点,产品 as 非叶结点的上级
from #tmp t
union all
select distinct 产品,产品,0
from #t where 产品 not in(select 组件 from #t)
order by 根,产品,组件
--删除测试环境
drop table #t,#tmp/*--测试结果
根 非叶结点 非叶结点的上级
----------- ----------- -----------
3200 3200 0
3200 2100 3200
30012 30012 0
30012 2200 2300
30012 2200 2400
30012 2500 2400
30012 2300 30012
30012 2400 30012
*/