在SQL Server递归中运行Total

时间:2013-12-30 11:43:55

标签: sql sql-server-2008

CREATE TABLE #tblTasks
    (
    TaskID int,
    BasedOn int,
    Interval int
    )

INSERT INTO #tblTasks
    (TaskID, BasedOn, Interval)
SELECT 1, 2, 5 UNION ALL
SELECT 2, 3, 3 UNION ALL
SELECT 3, 4, 2

;WITH rCTE(TaskID, BasedOn, Interval, TaskLevel) AS
(
SELECT TaskID, BasedOn, Interval, 1 AS TaskLevel
FROM #tblTasks
WHERE TaskID = 1
UNION ALL
SELECT e.TaskID, e.BasedOn, e.Interval, TaskLevel + 1
FROM #tblTasks e
INNER JOIN rCTE c ON e.TaskID = c.BasedOn
)

SELECT * FROM rCTE

DROP Table #tblTasks

上面的代码产生了这个输出:

TaskID----BasedOn----Interval----TaskLevel

1----2----5----1

2----3----3----2

3----4----2----3

我需要一个间隔列的运行总计。所以我需要第5列,使用上面的例子显示

TaskID----BasedOn---Interval----TaskLevel----TotalInterval

1----2----5----1----5

2----3----3----2----8

3----4----2----3----10

如何创建TotalInterval列?

1 个答案:

答案 0 :(得分:1)

您只需添加一点代码

CREATE TABLE #tblTasks
    (
    TaskID int,
    BasedOn int,
    Interval int
    )

INSERT INTO #tblTasks
    (TaskID, BasedOn, Interval)
SELECT 1, 2, 5 UNION ALL
SELECT 2, 3, 3 UNION ALL
SELECT 3, 4, 2

;WITH rCTE(TaskID, BasedOn, Interval, TaskLevel,IntervalTotal) AS
(
SELECT TaskID, BasedOn, Interval, 1 AS TaskLevel, Interval as IntervalTotal
FROM #tblTasks
WHERE TaskID = 1
UNION ALL
SELECT e.TaskID, e.BasedOn, e.Interval, TaskLevel + 1, c.IntervalTotal+e.Interval
FROM #tblTasks e
INNER JOIN rCTE c ON e.TaskID = c.BasedOn
)

SELECT * FROM rCTE

DROP Table #tblTasks