Retrieve previous row to subtract from current row by date

点点圈 提交于 2019-12-06 16:36:20

You can do this using correlated subqueries:

select NAV_date, NAV_value, (NAV_value / prev_value) - 1
from (select t.*,
             (select top 1 NAV_value
              from YOURTABLENAMEGOESHERE as t2
              where t2.NAV_date < t.NAV_date
              order by t2.NAV_date desc
             ) as prev_value
      from YOURTABLENAMEGOESHERE as t
     ) as t

I think you wanted something like this, using MySQL variables. Also, it seemed like you wanted to do a percent change calculation, but your formula is wrong. If not, let me know and this can get tweaked to precisely what you need:

SELECT
    nt.NAV_Date,
    nt.NetAssetValue,
    (@last_value := (SELECT NetAssetValue FROM NAV_Tbl WHERE NAV_Date < nt.NAV_Date ORDER BY NAV_Date DESC LIMIT 1)) AS last_value,
    IF(@last_value,(((nt.NetAssetValue - @last_value) / @last_value) * 100),NULL) AS percent_change
FROM
    NAV_Tbl nt,
    (SELECT
        @row_num:=0,
        @last_value:=0
    ) r
ORDER BY
    NAV_Date ASC

Result (2 left columns were original data, 2 right columns were calculated via query):

==============================================
| date       | value | last_value | percent  |
==============================================
| 2012-10-01 | 3500  | NULL       | NULL     |
| 2013-01-01 | 4500  | 3500       | 28.5714  |
| 2013-04-01 | 1000  | 4500       | -77.7778 |
| 2013-07-01 | 2500  | 1000       | 150.0000 |
| 2013-10-01 | 9000  | 2500       | 260.0000 |
==============================================
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!