简体   繁体   中英

Retrieve previous row to subtract from current row by date

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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