Oracle SQL 缺失年份计算最后价值和复利

沃尔特·里德

我在 Oracle 中有下表:

F1 F2 政府办公室
DC1 123 2021年 1000
DC1 123 2022年 1100
DC1 123 2023
DC1 123 2024
DC2 456 2021年 5000
DC2 456 2022年 6000
DC2 456 2023
DC2 456 2024

我想计算失踪多年(YEAR每分组2023和2024) F1F2基于该AMT最后一个可用日期(的YEAR2022),并乘以AMT2.1%,每年复利。

我用过这个LAST_VALUE功能

`(LAST VALUE(AMT IGNORE NULLS) OVER (PARTITION BY F1, F2 ORDER BY F1 F2 YEAR ROWS BETWEEN UNBOUNDED PRECEDING AND 1 PRECEDING) AS NEXT_AMT` 

获得每个分组的最后一个值(1100 和 6000),但是当我乘以 2.1% 时,我没有得到复利效应。

期望输出:

F1 F2 政府办公室 NEXT_AMT NEW_AMT
DC1 123 2021年 1000 1000
DC1 123 2022年 1100 1100
DC1 123 2023 1100 1123.1
DC1 123 2024 1100 1146.68
DC2 456 2021年 5000 5000
DC2 456 2022年 6000 6000
DC2 456 2023 6000 6126
DC2 456 2024 6000 6254.65
戈登·利诺夫

计算比率,然后使用算术进行乘法:

with t as (
      select t.*,
             max(case when year = 2022 then amt end) over (partition by f1, f2) as year_2022,
             (max(case when year = 2022 then amt end) over (partition by f1, f2) /
              max(case when year = 2021 then amt end) over (partition by f1, f2)
             ) as ratio
      from mytable t
     )
select t.*,
       coalesce(amt,
                year_2022 * power(ratio, year - 2022)
               ) as new_amt
from t;

编辑:

哎呀,我误读了这个问题。您实际上有一个固定的比率来增加金额。这更容易:

with t as (
      select t.*,
             max(case when year = 2022 then amt end) over (partition by f1, f2) as year_2022
      from mytable t
     )
select t.*,
       coalesce(amt,
                year_2022 * power(1.021, year - 2022)
               ) as new_amt
from t;

我也意识到你可能不想硬编码 2022。所以:

with t as (
      select t.*,
             last_value(case when amt is not null then year end ignore nulls) over (partition by f1, f2 order by year) as last_year,
             last_value(amt ignore nulls) over (partition by f1, f2 order by amt) as last_year_amt
      from mytable t
     )
select t.*,
       coalesce(amt,
                last_year_amt * power(1.021, year - last_year)
               ) as new_amt
from t;

是一个 db<>fiddle。

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章