Tuesday, March 22, 2011

Progressive sum

I have been struggling with progressive sum after reading some other people code who is using cursor to achieve this.

Before I provide the code, let me explain what is progressive sum. Progressive sum is usually used by accounting where you need to add or minus the value base on row level rather than give one value of sum. Below would be the example

IDinsertDatevalueProgressive_sum
12011-03-23 12:39:58.3172525
22011-03-23 12:39:58.3201540
32011-03-23 12:39:58.320-1525

As you can see on the row 1, we insert a value 25 and the progressive sum is 24. Once we insert value 15, the system automatically added 25+15 = 40.

Below would be the sample code that I use to produce the result above

create table #tmpAccounting
(
  ID int identity,
  insertDate datetime default getdate(),
  value float
)
insert into #tmpAccounting (value) values (25)
insert into #tmpAccounting (value) values (15)
insert into #tmpAccounting (value) values (-15)

select *, (select sum(value) from #tmpAccounting where insertDate<=a.insertDate and ID<=a.ID) as Progressive_Sum  from #tmpAccounting a order by ID

drop table #tmpAccounting

No comments:

Post a Comment