初步:使事情更容易,使date_
和實際date
。在第一天表示一個月的情況很常見。這就是我所做的。
選項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_ ;
選項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_ ;
在這兩種情況下,你會獲得:
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
你c檢查一切在dbfiddle here
謝謝。左連接方法更適合我,看起來不錯,清晰! –