SQL query to get Cumulative Sum of tree folder structure qty

时间:2015-08-14 22:46:06

标签: sql sql-server

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

1 个答案:

答案 0 :(得分:1)

请参阅Recursive Queries Using Common Table Expressions

html

输出(使用SQL小提琴):

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