简体   繁体   English

根据当前行和上一行的值填充一列mysql

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

I have a table tb1 like this: 我有一个这样的表tb1

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? 每个ID?

Preliminary: to make things easier, make date_ and actual date . 初步:为了使事情变得简单,请设置date_和实际的date It's common to represent a month by its first day. 通常在第一天代表一个月。 That's what I've done. 这就是我所做的。

Option 1: Use a subquery 选项1: 使用子查询

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 选项2 :( 左)在同一个月前与同一张表联接

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 您可以在dbfiddle检查一切在这里

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM