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
| ID | insertDate | value | Progressive_sum |
| 1 | 2011-03-23 12:39:58.317 | 25 | 25 |
| 2 | 2011-03-23 12:39:58.320 | 15 | 40 |
| 3 | 2011-03-23 12:39:58.320 | -15 | 25 |
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