有如下的数据,parentid表示父节点id,totalchilren表示该节点有几个子节点,total表示数量
id filecode parentid total children total 1 ws112 0 3 0 2 01 1 1 2 3 02 1 1 2 4 03 1 1 2 5 0101 2 0 3 6 0201 3 0 3 7 0301 4 0 3
|
我想输入ws112,得到如下的结果:
0101 6(2*3)
0201 6(2*3)
0301 6(2*3)
即不管01、02、03这些节点,直接得到ws112最低级的节点情况,请各位帮忙了。
讨论一:
create table A ( id int, filecode varchar(10), parentid int, totalchildren int, total int )
insert A select 1,'ws112',0,3,0 insert A select 2,'01',1,1, 2 insert A select 3,'02',1,1, 2 insert A select 4,'03',1,1, 2 insert A select 5,'0101',2,0, 3 insert A select 6,'0201',3,0, 3 insert A select 7,'0301',4,0, 3 create Function Find_num(@Code varchar(10)) returns @A table(filecode varchar(10),num int) as begin declare @T table(id int,filecode varchar(10),parentid int,totalchildren int,total int,lev int,num int) declare @lev int set @lev=1 insert @T select id,filecode,parentid,totalchildren,total,@lev as lev,@lev as num from A where filecode=@Code while @@rowcount>0 begin set @lev=@lev+1 insert @T select A1.id,A1.filecode,A1.parentid,A1.totalchildren,A1.total,@lev,A1.total*T.num from A A1, (select * from @T where lev=@lev-1) T where T.id=A1.parentid end insert @A select T.filecode,T.num from @T T where T.lev=(select top 1 lev from @T order by lev DESC ) return end select * from dbo.Find_num('ws112') |
点评:例子好像只能实现规则的树,应该说,这个例子是特例,其实你的树是一颗不规则的树,叶子的深度可能不一样.你想想实现的目标是:
1、查找到任一节点的全部叶子;
2、然后每一个叶子到目标节点之间的所有节点的total值相乘;
0101 6(2*3)
0201 6(2*3)
0301 6(2*3)
讨论二:
create table A ( id int, filecode varchar(10), parentid int, totalchildren int, total int )
insert A select 1,'ws112',0,3,0 insert A select 2,'01',1,1, 2 insert A select 3,'02',1,1, 2 insert A select 4,'03',1,1, 2 insert A select 5,'0101',2,0, 3 insert A select 6,'0201',3,0, 3 insert A select 7,'0301',4,0, 3 insert A select 8,'04',1,0,5 create function List_Leaf(@filecode varchar(10)) returns @LeafDetail table(filecode varchar(10),num int) As begin declare @TempTable table(id int, filecode varchar(10),parentid int,totalchildren int,total int,lev int,num int) declare @level int set @level = 0 insert @TempTable select *,@level,1 from A where filecode = @filecode while @@RowCount>0 begin set @level = @level + 1 insert @TempTable select A.*,@level,A.total*(T.num) from @TempTable T,A where T.lev = @level-1 and A.parentid = T.id end insert @LeafDetail select filecode,num from @TempTable where totalchildren = 0 return end select * from List_Leaf('ws112') go 测试结果: filecode num ---------- ----------- 04 5 0101 6 0201 6 0301 6 (所影响的行数为 4 行) |
点评:办法实现了需要的功能,不过,用了两个临时表,效率方面让人有点不满意.
讨论三: