How to implement decreasing balance using MySQL
P粉473363527
P粉473363527 2023-09-01 21:11:53
0
1
709
<p>How to create a declining balance query using mysql to calculate depreciation in accounting</p> <p>For example, the equipment costs $16,000, has an expected useful life of 5 years, and a depreciation rate of 40%. Depreciation</p> <pre class="brush:php;toolbar:false;">Year Starting book value Depreciation rate Depreciation amount Ending book value 1 16,000 40% 6,400 9,600 2 9,600 40% 3,840 5,760 3 5,760 40% 2,304 3,456 4 3,456 40% 1,382.40 2,073.60 5 2,073.60 40% 829.44 1,244.16</pre> <p>How can I create a function/query to obtain the above results? Thank you</p>
P粉473363527
P粉473363527

reply all(1)
P粉917406009

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.

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template