Calculating moving difference

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • Sumon

    #1

    Calculating moving difference

    Can some one please help me on this? I got 2 records by individual
    with some fileds, one associates with the min date and the other one
    assocaites with max date. So lay out looks as follows:

    Key_ID | Dates_Min_Max Avg_Weight
    1234 1/2/2004 12
    1234 1/2/2006 24

    I need to get the difference change between the weights for individual
    ids that is group by Key_ID and find the percent change. Some thing
    like this: (MAx_Row - Previos Row)/Previous Row * 100.

    How to do this? How do I get the previos row between 2 records if I
    order by the date? Any suggestions? Thanks

  • Bill Karwin

    #2
    Re: Calculating moving difference

    Sumon wrote:[color=blue]
    > I need to get the difference change between the weights for individual
    > ids that is group by Key_ID and find the percent change. Some thing
    > like this: (MAx_Row - Previos Row)/Previous Row * 100.[/color]

    Whenever you compare values on two rows, you usually have to do a JOIN
    to get them both on the same row of the result set, so you can compare
    the values.

    SELECT ((t2.avg_weight - t1.avg_weight) / t1.avg_weight) * 100
    AS pct_difference
    FROM tablename AS t1 JOIN tablename AS t2
    ON t1.key_id = t2.key_id AND t1.dates_min_ma x < t2.dates_min_ma x;

    Regards,
    Bill K.

    Comment

    Working...