Recursive sum in tree structure

后端 未结 5 2017
走了就别回头了
走了就别回头了 2020-12-01 03:05

I have a tree struture in a single table. The table is a tree of categories that can be nested endlessly. Each category has a ProductCount column that tells how many product

5条回答
  •  眼角桃花
    2020-12-01 03:43

    Actually this could be a good use of HIERARCHYID in SQL Server..

    CREATE TABLE [dbo].[CategoryTree]
    (
        [Id] INT,
        [ParentId] INT,
        [Name] VARCHAR(100),
        [ProductCount] INT
    )
    GO
    
    INSERT [dbo].[CategoryTree]
    VALUES
        (1, -1, 'Cars', 0),
        (2, -1, 'Bikes', 1),
        (3, 1, 'Ford', 10),
        (4, 3, 'Mustang', 7),
        (5, 3, 'Focus', 4)
        --,(6, 1, 'BMW', 100)
    GO
    

    Query

    WITH [cteRN] AS (
        SELECT *,
            ROW_NUMBER() OVER (
                PARTITION BY [ParentId] ORDER BY [ParentId]) AS [ROW_NUMBER]
        FROM  [dbo].[CategoryTree]
    ),
    [cteHierarchy] AS (
        SELECT CAST(
                CAST(hierarchyid::GetRoot() AS VARCHAR(100))
                + CAST([ROW_NUMBER] AS VARCHAR(100))
                + '/' AS HIERARCHYID
            ) AS [Node],
            *
        FROM [cteRN]
        WHERE [ParentId] = -1
        UNION ALL
        SELECT CAST(
                hierarchy.Node.ToString()
                + CAST(RN.[ROW_NUMBER] AS VARCHAR(100)
            ) + '/' AS HIERARCHYID),
            rn.*
        FROM [cteRN] rn
        INNER JOIN [cteHierarchy] hierarchy
            ON rn.[ParentId] = hierarchy.[Id]
    )
    SELECT x.[Node].ToString() AS [Node],
        x.[Id], x.[ParentId], x.[Name], x.[ProductCount],
        x.[ProductCount] + SUM(ISNULL(child.[ProductCount],0))
            AS [ProductCountIncludingChildren]
    FROM [cteHierarchy] x
    LEFT JOIN [cteHierarchy] child
        ON child.[Node].IsDescendantOf(x.[Node]) = 1
        AND child.[Node] <> x.[Node]
    GROUP BY x.[Node], x.[Id], x.[ParentId], x.[Name], x.[ProductCount]
    ORDER BY x.[Id]
    

    Result

    Results screenshot

提交回复
热议问题