Click here to Skip to main content
15,885,366 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
Dear Friends,

I want to calculate the vehicle cost, reducing the 10% every year.
How to derive this in query, enclosed the sample query

Select '2010'=600000,'2011'=600000-(600000*10)/100,'2012'=540000-(540000*10)/100,'2013'=486000-(486000*10)/100
Posted

We know the Formula of compound interest in P(1-r/100)^n<br />
so, just implement this in SQl.


Like this.
SQL
declare @P as decimal(18,2)
declare @rate as decimal(18,2)
declare @Yr as int
set @p=60000 --initial amount
set @rate=10 --rate of reduce 10%
set @Yr=2010-- starting year is 2010

declare @passYr as int
set @passYr=2011 -- calculating for the year of 2011

declare @res as decimal(18,2)
set @res=0
-- we know the formula of compound interest is p(1-r/100)^n

declare @pw as int
declare @yrD as int
set @yrD=@passYr-@Yr

set @pw=0
while @pw<@yrD -- loop for ^n year 
begin
set @res=(1-@rate/100)
set @pw=@pw+1
End

select (@P*@res)


You can just Use Power instead of While Loop .
See Ref.
https://msdn.microsoft.com/en-us/library/ms174276.aspx[^]
 
Share this answer
 
v2
you can use the following way to accomplish the given scenario.

this one is a reducing balance logic for each year. so if you give a range of the year to calculate the result you can use the following:

SQL
Declare @startYear int = 2000
		, @endYear int = 2010
		, @amt as int = 60000
		, @RunningTotal as int = 0;

DECLARE @t TABLE
(
  TID INT PRIMARY KEY,  
  pct int,
  RunningTotal int
);


------------- Tally table generation
;With tally
as
(
	select TOP 1000 ROW_NUMBER()Over(Order by (Select NULL)) -1 AS Rn
	from  sys.all_columns c
)


--- insert the data in table 
insert into @t
select @startYear + rn as years, case when rn = 0 then 0 else 10 end pct, 0.0
from tally
Where (@startYear + rn) <= @endYear

----------- Applied Quirky method 
UPDATE @t
  SET @RunningTotal = RunningTotal = (@amt - ((@amt * pct)/100))
			, @amt = @RunningTotal
			, pct = 10
  FROM @t
option (maxdop 0);	--- this will stop parallelism  

----------- Result
select * from @t

For more understanding on Quirky check this Link. Most of the people will say this is a undocumented way but i am using this approach from SQL SERVER 2000 till 2012 its and its working.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900