简体   繁体   中英

Updating table with the minimum date in a range that is greater than the current date in the row, in another column

"Is there a way to update the column (NEXT_DATE) in a table (RATES) in such a way that the rows reflect the minimum FUTURE_DATE in the range that is greater than the FUTURE_DATE in that row.

The range of dates from which to select the NEXT_DATE value should be confined to the set defined by the YIELD_CURVE_KEY.

Also, the row with the last (ie greatest) value for each YIELD_CURVE_KEY set should be updated in the NEXT_DATE column with the value (FUTURE_DATE + 1)".

Please see the example of how the table should look below (date format in US style). Thanks for looking!

TABLE = RATES

MARKET_DATE  YIELD_CURVE_KEY    FUTURE_DATE VALUE           NEXT_DATE
7/22/19      AUD-AUD OIS    7/22/19         1.000000    7/24/19
7/22/19      AUD-AUD OIS    7/24/19         0.999945    7/31/19
7/22/19      AUD-AUD OIS    7/31/19         0.999756    8/26/19
7/22/19      AUD-AUD OIS    8/26/19         0.999064    9/24/19
7/22/19      AUD-AUD OIS    9/24/19         0.998335    10/24/19
7/22/19      AUD-AUD OIS    10/24/19    0.997633    11/25/19
7/22/19      AUD-AUD OIS    11/25/19    0.996939    12/24/19
7/22/19      AUD-AUD OIS    12/24/19    0.996349    1/24/20
7/22/19      AUD-AUD OIS    1/24/20         0.995727    1/25/20
7/22/19      EUR-EONIA OIS  7/22/19         1.000000    7/25/19
7/22/19      EUR-EONIA OIS  7/25/19         1.000031    8/1/19
7/22/19      EUR-EONIA OIS  8/1/19          1.000102    8/2/19

A general solution would use a correlated subquery:

update rates
    set next_date = (select coalesce(min(r2.future_date), max(m.max_future_date))
                     from rates r2 cross join
                          (select max(future_date + 1) as max_future_date
                           from rates
                          ) m left join
                          rates r2
                         on r2.yield_curve_key = r.yield_curve_key and
                            r2.future_date > rates.future_date
                    );

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