Running Total in Select Query

  • I want to get the running total of an amount field that I calculate on the fly in a select query.

    Example:

    DECLARE @RunningTotal MONEY

    SET @RunningTotal = 0

    SELECT

    Count,

    (Amount * Count) NewAmt,

    (@RunningTotal + Amount * Count * .01) AS RunningTotal

    FROM TableA

    Sample Output:

    TableAId     NewAmt       RunningTotal

    1               100             1.00

    2               200             5.00

    3               300             14.00

    4               400             30.00

    Please help me with the query.

    Thanks,

    -NS.

  • DECLARE @totals TABLE(

     Code CHAR(4),

     Amount MONEY,

     Year INT)

    INSERT @totals(

     Code,

     Amount,

     Year)

     SELECT 'AAAA',100000,'1998' UNION ALL

     SELECT 'AAAA',200000,'1999' UNION ALL

     SELECT 'AAAA',300000,'2000' UNION ALL

     SELECT 'BBBB',100000,'1998' UNION ALL

     SELECT 'BBBB',100000,'2000' UNION ALL

     SELECT 'CCCC',100000,'1999'

    SELECT

     t.Code,

     t.Amount,

     t.Year,

     (SELECT SUM(Amount) FROM @totals WHERE Year <= t.Year AND Code = t.Code) AS RtotalField

    FROM

     @totals t

    GROUP BY

     t.Code,

     t.Amount,

     t.Year

    Derrick Leggett
    Mean Old DBA
    When life gives you a lemon, fire the DBA.

  • I do not have any sequential value as the 'year' in the above example and hence it can't be sorted on a field to get the sum of all previous values till that record.

    -NS.

  • Presumably you have an ordering sequence?

    Without details of your table structure the only way that I can think of doing it is by using a cursor, however I would tend to do running totals in a front end app, rather than within the stored procedure.

  • in the temp table, define with an identity id field.

    insert into the other fields, then use the identity to sort on.

    dan

  • You dont have to have an ordering sequence per se. It is enough to have a PK or Unique Constraint on the table to order by.

    In your example it seems to me that field TableAId would serve this purpose.

    And You can use the method proposed by Derrick Leggett and order by PK or UC in the table.

    /rockmoose


    You must unlearn what You have learnt

  • I defined a temp table and got it working.

    Thanks for all your help.

    -NS.

Viewing 7 posts - 1 through 6 (of 6 total)

You must be logged in to reply to this topic. Login to reply