getting cumulative values

  • I have a problem I was hoping someone could help with.

    I need to calculate a cumulative value from one of my tables.  The table looks like...

    IDSecondaryIdValue
    113.2
    121.3
    130.4
    214.8
    221.3
    311.5
    322.3

     

    The result I would like to see is an accumulation of the value column for each Id.  So, in this example, I would like to see a table like...

     

    IDSecondaryIdValueCumulativeValue
    113.23.2
    121.34.5
    130.44.9
    214.84.8
    221.36.1
    311.51.5
    322.33.8

     

    The combination of ID and Secondary Id make up the primary key for the table.  I know I could do this with a cursor, but generally I think cursors are bad and would prefer to avoid using one in this case.  Any help would be greatly appreciated.  Thanks.


    George Mastros
    Orbit Software, Inc.

  • I think this should do it:

    SELECT A.ID,

    A.SecondaryId,

    A.Value,

    SUM(B.Value) AS CumulativeValue

    FROM YourTable A

    JOIN YourTable B ON B.Id <= A.Id

    AND ((B.Id = A.Id AND B.SecondaryId <= A.SecondaryId) OR (B.Id < A.Id))

    GROUP BY A.ID,

    A.SecondaryId,

    A.Value

    --
    Adam Machanic
    whoisactive

  • select 1 as [ID], 1 as SecondaryID, 3.2 as Value into #temp

    union

    select 1,2, 1.3

    union

    select 1, 3, 0.4

    union

    select 2, 1, 4.8

    union

    select 2, 2, 1.3

    union

    select 3, 1, 1.5

    union

    select 3, 2, 2.3

    select id, secondaryID,value, CumulativeValue=value +

    ISNULL((select sum(value) from #temp where id=t.id and secondaryid<t.secondaryid),0)  from #temp t order by id, secondaryid

  • Thank you.  Your solution worked. 

    I keep forgetting abount using inequality operators while joining tables.


    George Mastros
    Orbit Software, Inc.

Viewing 4 posts - 1 through 3 (of 3 total)

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