Search code examples
mysqlupdating

populate a column based on current row and previous row's value mysql


I have a table tb1 like this:

ID      DATE_     STATs 
1      2007-01     0.2
1      2007-02     0.12
1      2007-03     0.42
1      2007-04     0.23
1      2007-05     0.26
1      2007-06     0.17
2      2007-01     0.33
2      2007-02     0.14
2      2007-03     0.21
2      2007-04     0.35
2      2007-05     0.67
2      2007-06     0.07

How do I add an additional column computed by:

(1+current.STATs) / (1+priorMonth.STATs) - 1

for each ID?


Solution

  • Preliminary: to make things easier, make date_ and actual date. It's common to represent a month by its first day. That's what I've done.

    Option 1: Use a subquery

    SELECT
        id, date_, 
        (1.0 + stats) / (1.0 + (SELECT stats FROM t t_prev WHERE t_prev.id = t.id AND t_prev.date_ = t.date_ - interval 1 month)) - 1.0 AS r
    FROM
        t
    ORDER BY
        id, date_ ;
    

    Option 2: (Left) Join with the same table, one month before

    SELECT
        curr.id, curr.date_, (1.0 + curr.stats) / (1 + prev.stats) - 1.0 AS r
    FROM
        t AS curr
        LEFT JOIN t AS prev 
            ON prev.id = curr.id AND prev.date_ = curr.date_ - interval 1 month 
    ORDER BY
       curr.id, curr.date_ ;
    

    In both cases, you'll get:

    id | date_      |                    r
    -: | :--------- | -------------------:
     1 | 2007-01-01 |                 null
     1 | 2007-02-01 | -0.06666667121979919
     1 | 2007-03-01 |  0.26785713418538926
     1 | 2007-04-01 | -0.13380280596423388
     1 | 2007-05-01 | 0.024390232674120105
     1 | 2007-06-01 | -0.07142856298120104
     2 | 2007-01-01 |                 null
     2 | 2007-02-01 | -0.14285715085991468
     2 | 2007-03-01 |  0.06140350246565207
     2 | 2007-04-01 |  0.11570248045838927
     2 | 2007-05-01 |  0.23703705486119708
     2 | 2007-06-01 | -0.35928144335037204
    

    You can check everything at dbfiddle here