Link to home
Start Free TrialLog in
Avatar of vbjohn
vbjohn

asked on

Running Total & Count

Is there a way that I could keep a Running Total & a Running Count?

For Example:
Running Count.
Total of 8 Records..
1,2,3,4,5,6,7,8

Running Total.
1 - 1
10 - 11
20 - 31
100 - 131
Avatar of Guy Hengel [angelIII / a3]
Guy Hengel [angelIII / a3]
Flag of Luxembourg image

If the records have primary key like this:

RecordID  Value
1         1
2         10
3         20
4         100
aso

Then:

SELECT
  R.RecordID,
  R.Value,
  TunningTotal = (SELECT SUM(T.VALUE) FROM YourTable T WHERE T.RecordID <= R.RecordID )
FROM YourTable R

Cheers

On a large table, you are probably better off using a CURSOR for table access and calculating the running count and running total with other code.  I know that CURSORs should generally be avoided but in a case like this I see no acceptable alternative.
Avatar of vbjohn
vbjohn

ASKER

So how would I do that?  With the Cursors.  I have no experience with Stored Procedures.  Any coding examples please let me know.
there is a function, a really simple one, that I regularly forgot, and than re - create it again, when I have time, it is arithmetic progression. Right now I am between forgot and  re - create :).
If your increment is predictable, and you expect that rows will not be deleted some time in the future, performance and code will benefit of using this function instead of really summing up the values.
ASKER CERTIFIED SOLUTION
Avatar of Scott Pletcher
Scott Pletcher
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial