Retrieve previous row to subtract from current row by date

醉酒当歌 提交于 2019-12-08 06:16:56

问题


I have a table with only 2 fields: NAV_Date and NetAssetValue.

NAV_Date is the last day of a quarter.

+----------+--------------+
|NAV_Date  |NetAssetValue |
+----------+--------------+
|12/31/2012|        $4,000|
+----------+--------------+
|03/31/2013|        $5,000|
+----------+--------------+

I am attempting to write a query that subtracts the more recent from the previous. Currently, my query simply selects all values within the table. I know to perform this I would have to retrieve the prior record each time through, however I'm not sure how to do that.

Ultimately I will use ((CurrentValue/PreviousValue) - 1) and store the value as a percent to return the difference.

I will also be performing this for yearly values. Does anyone have an example if they did something similar or perhaps a clue to get me started?

The reason I am asking is because I searched for a solution but could not find any useful examples where there was not an autonumber or an ID field.


回答1:


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



回答2:


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 |
==============================================


来源:https://stackoverflow.com/questions/21244681/retrieve-previous-row-to-subtract-from-current-row-by-date

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!