Click here to Skip to main content
15,885,546 members
Please Sign up or sign in to vote.
5.00/5 (1 vote)
Hi,
I would like to use SUM or any other function to sum a series of
records as in the following example.

I have this table T1

Col1 Col2
1 20
2 10
1 10
2 5
1 20
3 10

and would like to obtain this result from a query

Col1 Col2 Col3
1 20 20
1 10 30
1 20 50
2 10 10
2 5 15
3 10 10

Column Col3 should carry forward and sum values from Col2
Posted

Hi,

Try this...

SQL
DECLARE @TblVariable Table
(
  col1 INT,
  col2 INT
);

INSERT INTO @TblVariable VALUES
(1,20),
(2,10),
(1,10),
(2,5),
(1,20),
(3,10);

With tblCTE as
(
Select Row_Number() OVER (Order by col1) as RowNumber,col1,col2 from @TblVariable
)

SELECT Col1,Col2,
( SELECT SUM(Col2) FROM tblCTE T2 WHERE T2.RowNumber <= T1.RowNumber 
  AND T1.Col1 = T2.Col1 GROUP BY Col1
) AS Col3 FROM tblCTE T1 GROUP BY Col1,Col2,RowNumber
ORDER BY Col1, RowNumber


Thank you..
 
Share this answer
 
Comments
Aarti Meswania 30-Oct-12 3:47am    
my 5+
damodara naidu betha 30-Oct-12 6:08am    
Thank you Aarti
Aarti Meswania 30-Oct-12 6:09am    
welcome :)
Hi,

See the below links.
It might be help you.

Query for running total in SQL Server[^]

Query for running total in SQL Server[^]
 
Share this answer
 
Comments
[no name] 29-Oct-12 7:58am    
But i m having a single table and the number of columns are 3..can u plz give some some example by putting some values
Try using a correlated subquery.

SQL
select
a.Col1, a.Col2, 
(
select sum(b.Col2)
from t as b
where b.Col1 = a.Col1
) as col3 
from 
t as a;
GO



You can also do it with a self-join:


SQL
select a.Col1,a.Col2,sum(b.Col2) as Col3
from T1 as a
inner join T1 as b on b.Col1=a.Col1 
group by a.Col1,a.Col2


but I supppose the performance will be slightly worse (depends on additional filter criteria).
 
Share this answer
 
Comments
[no name] 29-Oct-12 8:05am    
Hi Bitla: please check this question in the given link and plz help me out in that
http://www.codeproject.com/Questions/485430/needplushelpplusinplusaddingplustheplusvaluespluso
Here is a sample approach.

SQL
CREATE TABLE #Temp
(
	ID INT IDENTITY(1,1),
	Col1 INT,
	Col2 INT
)

INSERT INTO #Temp
SELECT 1, 20 UNION ALL
SELECT 2, 10 UNION ALL
SELECT 1, 10 UNION ALL
SELECT 2,  5 UNION ALL
SELECT 1, 20 UNION ALL
SELECT 3, 10



SELECT Col1,Col2,
(
SELECT SUM(Col2) FROM #Temp T2
WHERE T2.ID <= T1.ID AND T1.Col1 = T2.Col1
GROUP BY Col1
) AS Col3
FROM #Temp T1
GROUP BY Col1,Col2,ID
ORDER BY Col1, ID

DROP TABLE #Temp


Hope this helps.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900