How to get Running Value in SQL

Hello Guys,

One day I was discussing with one of my colleague, he was trying to find out the running value of two columns. But he was facing some diffulty and was doing some tedious way to do it by using GridView on row databound get the first column value and doing someway.
I explained him there is more convenient way to do that with using SELF join in SQL. Here is an example:

CREATE TABLE RunningValue (Sr int identity(1,1),Amount1 numeric(18,0),  Amount2 numeric(18,0))

INSERT INTO RunningValue VALUES (1400,1100)
INSERT INTO RunningValue VALUES (1100,1200)
INSERT INTO RunningValue VALUES (1000,1500)
INSERT INTO RunningValue VALUES (1200,800)
INSERT INTO RunningValue VALUES (2000,1100)
INSERT INTO RunningValue VALUES (1460,2100)
INSERT INTO RunningValue VALUES (1400,1600)

SELECT Sr,Amount1, Amount2,
(SELECT sum(Amount1+Amount2) FROM RunningValue B WHERE B.Sr <= A.Sr)  as TotalRuningAmount
 FROM RunningValue A

Cheers,
ved pathak

Comments