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

有关sql树型结构统计的问题:
现有类似的表结构,其实的score字段是通过统计出来的,实际情况中是不存在这样一个表的。
要求统计出每个节点及这个节点的所有子结点的score值。

我现在用递归函数,对每个结点做一次递归,但效率不行,因为函数要不能访问临时表,我创建了临界的基本表,每次调用此过程的时候用统计出来的信息来填充此表,如果在并发的情况下,这样效率明显不行,
请高手指教。

CREATE TABLE tbTest
(id nvarchar(5),
 parentID nvarchar(5),
 score decimal(18,2)
)

insert into tbTest
select '1','',10
union all
select '2','1',30
union all
select '3','2',30
union all
select '4','1',50
union all
select '5','',10
union all
select '6','5',30

select * from tbTest


------最佳解决方案--------------------
--清远市
    
------其他解决方案--------------------
sf
------其他解决方案--------------------
咋一看,原来是火鸟大侠
------其他解决方案--------------------
db
------其他解决方案--------------------
你要什么结果 ,只要根? 还是任意节点?
------其他解决方案--------------------
/*
Microsoft SQL Server 2008 (RTM) - 10.0.1600.22 (Intel X86)   Jul  9 2008 14:43:34   Copyright (c) 
1988-2008 Microsoft Corporation  Enterprise Evaluation Edition on Windows NT 5.1 <X86> 
(Build 2600: Service Pack 3) 
 愿和大家共同进步
如有雷同、实属巧合
●●●●●2009-09-03 17:47:36.077●●●●●
 ★★★★★soft_wsx★★★★★
*/
--树型结构处理之双编号(广度深度排序)
if OBJECTPROPERTY(object_id('tb'),'isusertable')<>0 
  drop table tb
create table tb(ybh nvarchar(10),ebh nvarchar(10),beizhu nvarchar(1000))
insert tb
select '0001',null,'云南省'
union all select '0002','0001','昆明市'
union all select '0003','0001','昭通市'
union all select '0009','0001','大理市'
union all select '0008',null,'四川省'
union all select '0004',null,'贵州省'
union all select '0005','0002','五华区'
union all select '0007','0002','水富县'
union all select '0006','0005','西园路192号'
union all select '0010','0006','金色梧桐'
union all select '0011','0010','科技有限公司'
union all select '0015','0007','两碗乡'
union all select '0013','0015','两碗村'
union all select '0012','0013','某跨国集团董事长'
union all select '0014','0008','成都市'

--select * from tb
--广度排序(先显示第一层节点,再显示第二次节点......)
--定义辅助表
declare @level_tb table(bh nvarchar(10),level int)
declare @level int
set @level=0
insert @level_tb(bh,level)
select ybh,@level from tb where ebh is null
while @@ROWCOUNT>0
  begin
    set @level=@level+1
    insert @level_tb(bh,level)
      select ybh,@level 
        from tb a,@level_tb b
        where a.ebh=b.bh 
              and b.level=@level-1
  end 
  select a.*,b.* from tb a,@level_tb b where a.ybh=b.bh order by lev