CTE Hierachy下降,但从祖先中挑选出不是父母的孩子节点

说明

好的,标题可能有点多:)

我将在最后粘贴脚本。

想象下面的n元树

.  
|  
---1 **(25)**   
   |  
    -----1.1 **(13)**  
    |    |  
    |    ----1.1.1 (1)  
    |    |  
    |    ----1.1.2 **(7)**  
    |    |    |
    |    |    ----1.1.2.1 (4)        
    |    |    |
    |    |    ----1.1.2.2 (3)  
    |    |    
    |    ----1.1.3 (5)  
    |    
    -----1.2 (2)  
    | 
    |    
    -----1.3 (10)  

等等,在哪里根分支“。” 也可以有一个2,3,n分支,并且该分支也可以有任意给定节点的n分支的任意树形式。 可以这么说,每个节点末端的括号中的值就是节点上的值。 将它们想象为具有父帐户的子帐户的帐户是子帐户的总和。

我正在尝试与CTE做的是直接检索父级下的所有[子]帐户。 因此,为了提供1.1作为搜索点,它将检索树的整个分支。 但是,如果我试图聪明地总结返回的值,我在1.1.2中增加两次,一次是通过其子账户的总和,第二次是它本身包含的值的总和。

我会如何去做这样的事情?

谢谢你一个:)

这里是脚本:

脚本

SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

CREATE TABLE [dbo].[Account](
    [ID] [nvarchar](50) NOT NULL,
    [ParentID] [nvarchar](50) NULL,
    [Value] [float] NOT NULL,
    [HasChild] [bit] NOT NULL,
 CONSTRAINT [PK_Account] PRIMARY KEY CLUSTERED 
(
    [ID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF,     ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]

GO

ALTER TABLE [dbo].[Account]  WITH CHECK ADD  CONSTRAINT [FK_Account_Account] FOREIGN     KEY([ParentID])
REFERENCES [dbo].[Account] ([ID])
GO

ALTER TABLE [dbo].[Account] CHECK CONSTRAINT [FK_Account_Account]
GO

ALTER TABLE [dbo].[Account] ADD  CONSTRAINT [DF_Account_HasChild]  DEFAULT ((0)) FOR     [HasChild]
GO

CTE脚本

WITH 
DescendToChild([ID],ParentID,Value)
AS
(

    --base case
    SELECT [ID],ParentID,Value FROM Account
    Where ParentID = '1.1'


    UNION ALL

    ----recursive step
    SELECT
        A.[ID],A.ParentID,A.Value FROM Account as A
        INNER JOIN DescendToChild D on A.ParentID = D.ID
)
select * from DescendToChild;

以下是基于您的示例数据的解决方案。 它仅通过总结没有孩子的节点来工作:

DECLARE @tree TABLE
(id INT
,parentid INT
,nodeName VARCHAR(10)
,VALUE INT
)

INSERT @tree (id,parentid,nodeName,VALUE)
VALUES
(1,NULL,'.',NULL),
(2,1,'1',25),
(3,2,'1.1',13),
(4,2,'1.2',2),
(5,2,'1.3',10),
(6,3,'1.1.1',1),
(7,3,'1.1.2',7),
(8,3,'1.1.3',5),
(9,7,'1.1.2.1',4),
(10,7,'1.1.2.2',3)


;WITH recCTE
AS
(
     SELECT id, parentid, nodeName, value, 
            CASE WHEN EXISTS (SELECT 1 FROM @tree AS t1 WHERE t1.parentid = t.id) THEN 1 ELSE 0 END AS hasChildren
     FROM @tree AS t
     WHERE nodeName = '1.1'

     UNION ALL

     SELECT t.id, t.parentid, t.nodeName, t.value, 
            CASE WHEN EXISTS (SELECT 1 FROM @tree AS t1 WHERE t1.parentid = t.id) THEN 1 ELSE 0 END AS hasChildren
     FROM @tree AS t
     JOIN recCTE AS r
     ON   r.id = t.parentid

)
SELECT SUM(VALUE)
FROM recCTE 
WHERE hasChildren = 0
OPTION (MAXRECURSION 0)

http://social.msdn.microsoft.com/Forums/en-US/transactsql/thread/959fe835-e43d-4995-882c-910f3aa0ff68/

链接地址: http://www.djcxy.com/p/60219.html

上一篇: CTE Hierachy descending but picking up child nodes not parents from ancestor

下一篇: Is it possible to have a function without a parameter in t