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

In the above table result set i need the cumm column values as like this , how to do this with an query , can someone help?

4

2 回答 2

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
于 2013-05-20T06:24:54.863 回答
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 小提琴

于 2013-05-20T07:01:41.087 回答