Click here to Skip to main content
15,908,901 members
Please Sign up or sign in to vote.
1.00/5 (2 votes)
How can i get this type of output
A b
5 5
6 11
3 14

MEans b=b+a
Posted

I think this is a great example of what you are trying to do

http://www.sqlservercentral.com/Forums/Topic707938-392-1.aspx#bm708015[^]
 
Share this answer
 
Try this:
SQL
DECLARE @myValues TABLE (ID INT IDENTITY(1,1), A INT)

INSERT INTO @myValues (A)
SELECT 5 AS A
UNION ALL SELECT 6
UNION ALL SELECT 3


;WITH CTEBalance
AS
(
	SELECT ID, A 
	FROM @myValues
) 
SELECT B.ID, B.A, SUM(C.A) AS Balance 
FROM CTEBalance AS B INNER JOIN CTEBalance AS C ON B.ID >= C.ID
GROUP BY B.ID, B.A
ORDER BY B.ID

or
SQL
SELECT t1.ID, SUM(t2.A) AS Balance
FROM @myValues AS t1 INNER JOIN @myValues AS t2 ON t1.ID >= t2.ID
GROUP BY t1.ID
ORDER BY t1.ID


Result:
ID  A   Balance
1   5   5
2   6   11
3   3   14


If you do not have ID field, you need to use ROW_NUMBER()[^] function. In case of trouble, let me know.
 
Share this answer
 
v3

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