如何在单独的列中将值添加为累积值?

时间:2013-05-20 05:52:08

标签: sql-server-2008

COL COL1    COL2    SUM cumm
1   2   3   6    6
4   5   6   15   21 
7   8   9   24   45

在上面的表结果集中,我需要像这样的cumm列值,如何使用查询执行此操作,有人可以帮忙吗?

2 个答案:

答案 0 :(得分:3)

试试这个 -

<强>查询:

DECLARE @temp TABLE
(
      Col1 INT
    , Col2 INT
    , Col3 INT
    , Col4 INT
)

INSERT INTO @temp (Col1, Col2, Col3, Col4)
VALUES 
    (1,   2,   3,   6),
    (4,   5,   6,   15),
    (7,   8,   9,   24)

SELECT 
      Col1
    , Col2
    , Col3
    , Col4
    , SUM_cumm = SUM(Col4) OVER(
        ORDER BY Col4 
        ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW)
FROM @temp

<强>输出:

Col1        Col2        Col3        Col4        SUM_cumm
----------- ----------- ----------- ----------- -----------
1           2           3           6           6
4           5           6           15          21
7           8           9           24          45

答案 1 :(得分:2)

您可以使用 CTE

create table table1
(
    COL int,
    COL1 int,
    COL2 int,
    COL3 int
)
insert into table1
(COL,COL1,COL2,COL3)
values
(1,   2,   3,   6),
(4,   5,   6,   15), 
(7,   8,   9,   24)

select 
rank() OVER (ORDER BY COL3) as [Rank],
t1.COL,
t1.COL1,
t1.COL2,
t1.COL3
into #temp1
from table1 t1

;WITH x AS
(
    SELECT 
        [Rank],
        COL,
        COL1,
        COL2,
        COL3,
        Total=COL3
    FROM #temp1
    WHERE [Rank] = 1
    UNION ALL
    SELECT 
        y.[Rank],
        y.COL,
        y.COL1,
        y.COL2,
        y.COL3,
        x.Total+(y.COL3)
    FROM x INNER JOIN #temp1 AS y
    ON y.[Rank] = x.[Rank] + 1
)
SELECT 
    COL,
    COL1,
    COL2,
    COL3,
    Total
FROM x
OPTION (MAXRECURSION 100);

<强> SQL FIDDLE