SQL中树形结构数据的分层更新查询

时间:2018-06-29 05:25:11

标签: sql sql-server

create table #tmp(ChildID nvarchar(50),ParentID nvarchar(50), Percentage numeric(8,2))
insert into #tmp values ('1', NULL,NULL)
insert into #tmp values ('1.1', '1',89)
insert into #tmp values ('1.2', '1',NULL)
insert into #tmp values ('1.2.1','1.2',96)
insert into #tmp values ('1.2.2', '1.2',NULL)
insert into #tmp values ('1.2.2.1', '1.2.2',87)
insert into #tmp values ('1.2.2.2', '1.2.2',NULL)
insert into #tmp values ('1.2.2.2.1', '1.2.2.2',87)

enter image description here

我正在尝试CTE更新,但是还不能攻击预期的结果。能帮上忙吗?

3 个答案:

答案 0 :(得分:0)

我想这就是你想要的:

With cte as
(Select ChildId, Sum(Percentage) as [percent] from (
Select t1.ChildID,t1.Percentage as oldPercent, t2.ParentID, t2.Percentage from #tmp t1 
join #tmp t2 on t2.ParentID like t1.ChildID +'%')c 
group by ChildId
)
Update #tmp 
set Percentage = cte.[percent]
from #tmp join cte
on #tmp.ChildID = cte.ChildID

答案 1 :(得分:0)

看看这个。

DECLARE @tmp TABLE  (ChildID NVARCHAR(50)
                   ,ParentID NVARCHAR(50)
                   ,Percentage NUMERIC(8, 2)
                   )
INSERT  INTO @tmp   VALUES  ('1', NULL, NULL) 
INSERT  INTO @tmp   VALUES  ('1.1', '1', 89)
INSERT  INTO @tmp   VALUES  ('1.2', '1', NULL)
INSERT  INTO @tmp   VALUES  ('1.2.1', '1.2', 96)
INSERT  INTO @tmp   VALUES  ('1.2.2', '1.2', NULL)
INSERT  INTO @tmp   VALUES  ('1.2.2.1', '1.2.2', 57)
INSERT  INTO @tmp   VALUES  ('1.2.2.2', '1.2.2', NULL)
INSERT  INTO @tmp   VALUES  ('1.2.2.2.1', '1.2.2.2', 62);

WITH    cteTree
          AS (SELECT    t1.ChildID, t1.childid AS OriginalID
              ,         t1.Percentage
              FROM      @tmp t1
              UNION ALL
              SELECT t2.ChildID
              ,      c.OriginalID
              ,      t2.Percentage
              FROM      @tmp t2
              JOIN cteTree c ON t2.parentID = c.ChildID
             )

SELECT OriginalID AS ChildID, SUM(cteTree.Percentage)
FROM cteTree
GROUP BY OriginalID
ORDER BY cteTree.OriginalID

其他人都非常接近,但是需要略有不同的迭代,如果您不经常使用它,迭代可能会很棘手。

答案 2 :(得分:-1)

您可以尝试以下方法:

DECLARE  @temp table(ChildID nvarchar(50),ParentID nvarchar(50), Percentage numeric(8,2))
insert into @temp values ('1', NULL,NULL)
insert into @temp values ('1.1', '1',89)
insert into @temp values ('1.2', '1',NULL)
insert into @temp values ('1.2.1','1.2',96)
insert into @temp values ('1.2.2', '1.2',NULL)
insert into @temp values ('1.2.2.1', '1.2.2',57)
insert into @temp values ('1.2.2.2', '1.2.2',NULL)
insert into @temp values ('1.2.2.2.1', '1.2.2.2',62)

;With cte
AS
(
select  * ,ROW_NUMBER()Over(Order by (select NULL))Rn  from @temp
)
Select 
ChildID
,ParentID
,Case when Percentage IS NULL Then (select SUM(c.Percentage) From Cte c Where c.Rn>cte.Rn) Else Percentage END Percentage
from cte