P粉9174060092023-09-02 14:19:13
You can use recursive CTE to get the results you want. For example:
with recursive p as (select 16000.00 as book_value, 0.4 as rate, 5 as total_years), y (year, book_value_start, rate, depreciation, book_value_end) as ( select 1, book_value, rate, round(rate * book_value, 2), book_value - round(rate * book_value, 2) from p union all select y.year + 1, y.book_value_end, y.rate, round(y.rate * y.book_value_end, 2), y.book_value_end - round(y.rate * y.book_value_end, 2) from y cross join p where y.year < p.total_years ) select * from y order by year
result:
year book_value_start rate depreciation book_value_end ----- ----------------- ----- ------------- -------------- 1 16000.00 0.4 6400.00 9600.00 2 9600.00 0.4 3840.00 5760.00 3 5760.00 0.4 2304.00 3456.00 4 3456.00 0.4 1382.40 2073.60 5 2073.60 0.4 829.44 1244.16
View running examples on DB Fiddle.
Note: All three parameters are defined in the second line. If you want to change the starting value, interest rate, or number of years, make your changes there.