简体   繁体   中英

SQL query to get Cumulative Sum of tree folder structure qty

I have Tree structure table in SQL and I want sum of all child node and node itself . I am able to do cumulative sum but against node specific

SQL Fiddle

But I want output like this

Id  RootId  FullName    QTY CumulativeSum
1   -1         ROOT 1   0   45
2   1      SUB ITEM 1.1 9   9
3   1   SUB ITEM 1.2    3   11
4   3   SUB ITEM 1.2.1  1   1
5   3   SUB ITEM 1.2.2  7   7
6   1   SUB ITEM 1.3    5   25
7   6   SUB ITEM 1.3.1  2   20
8   7   SUB ITEM 1.3.1.1    18  18

I have tried query like

SELECT t1.Id,t1.RootId,t1.FullName,t1.QTY,
SUM(t1.QTY) OVER(ORDER BY t1.Id ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT
ROW) AS CumulativeSum
FROM #Tree t1
ORDER BY t1.id

But its not giving me desired solution

See Recursive Queries Using Common Table Expressions .

WITH cte (Id, RootId, ParentId, FullName, QTY) AS (
  SELECT Id, Id, RootId, FullName, QTY FROM Tree
  UNION ALL
  SELECT Tree.Id, cte.RootId, Tree.RootId, Tree.FullName, Tree.QTY
    FROM cte
    JOIN Tree ON Tree.RootId = cte.Id
)
SELECT RootId AS Id
     , MIN(CASE WHEN Id = RootId THEN ParentId END) AS RootId
     , MIN(CASE WHEN Id = RootId THEN FullName END) AS FullName
     , MIN(CASE WHEN Id = RootId THEN QTY END) AS QTY
     , SUM(QTY) AS CumulativeSum
  FROM cte
 GROUP BY RootId
 ORDER BY Id

Output (using the SQL Fiddle):

Id  RootId  FullName          QTY  CumulativeSum
--  ------  --------          ---  -------------
1   -1      ROOT 1            0    45
2   1       SUB ITEM 1.1      9    9
3   1       SUB ITEM 1.2      3    11
4   3       SUB ITEM 1.2.1    1    1
5   3       SUB ITEM 1.2.2    7    7
6   1       SUB ITEM 1.3      5    25
7   6       SUB ITEM 1.3.1    2    20
8   7       SUB ITEM 1.3.1.1  18   18
9   -1      ROOT 2            0    0
10  -1      ROOT 3            0    22
11  10      SUB ITEM 3.1      1    22
12  11      SUB ITEM 3.2      10   21
13  12      SUB ITEM 3.3      4    11
14  13      SUB ITEM 3.3.1    2    2
15  13      SUB ITEM 3.3.2    5    5

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM