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?
Try this one -
Query:
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
Output:
Col1 Col2 Col3 Col4 SUM_cumm
----------- ----------- ----------- ----------- -----------
1 2 3 6 6
4 5 6 15 21
7 8 9 24 45
You can use 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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With