Question
· Oct 28, 2019

A simple running total in Cache SQL

Can anyone tell me how to add a simple running total in Cache SQL.

I'm selecting a quantity in the first column and want a running total in the second:

9 ,   9

2 , 11

7 , 18

Discussion (9)0
Log in or sign up to continue

Christopher,

Your cursor method was pretty close to how I've ended up solving my task.

The problem I was trying to solve involved comparing a comulativeTotal with a previouscomulativeTotal.   I had a go at trying to do this in SQL this morning but due to the fact I'd be joining back to the same table once to get the comulative total and yet again to get back to the previouscomulative total it meant the query took ages.   I went with a embedded cursor in object script and created a recordset at the end to pass back both  comulativeTotal  and previouscomulativeTotal at the same time.   The iterative approach worked much better here as the two totals were close (one iteration away) ..
 

drop table if exists [stair];
create table [stair] (
    [purse] integer
);
insert into [stair] (purse) values(9);
insert into [stair] (purse) values(2);
insert into [stair] (purse) values(7);
--++++++
declare cursorA cursor 
for select purse from [dbo].[stair]
declare @col integer
declare @tot integer
open cursorA
set @tot = 0
fetch next from cursorA into @col
while @@FETCH_STATUS=0
begin
   set @tot = @tot + @col;
   print convert(varchar,@col) + ', ' + convert(varchar,@tot);
   fetch next from cursorA INTO @col;
end
close cursorA;
deallocate cursorA;
drop table [stair];