使用sql计算年复利

compounding yearly interest using tsql

我想创建一个 table 这样使用 sql 的复利。

name    rate    principal   year1   year2
A       .5      10          15       22.5
B       .0      10          10       10.0

我能够创建一个存储过程并将其硬编码为每个名称的两年利息,但这意味着我必须每增加一年就增加一年。是否有使用过程或仅使用视图的优雅有效的方法?

下面是你想要的吗?

declare @NbrofYears int, @Rate float, @Principle float

select @NbrofYears = 5, @Principle = 10, @rate = 0.5

;with cte as
(
select 1 as NbrOfYears, @Principle as Principle, @Rate as Rate
union all
select NbrOfYears + 1, Principle * (1 + @Rate), Rate
from cte
where NbrOfYears < @NbrofYears
)

select * from cte

您似乎需要复利计算和枢轴。这是 5 年的静态版本,如果您需要使持续时间动态化,则有很多动态旋转的示例。

编辑: 我忽略了 SQL 2005 标签 - 无法确认这是否适用于那个版本,因为我们是 SQL 2012/4这里。

CREATE TABLE #Test (
    Name CHAR(1),
    Rate MONEY,
    Principal MONEY
);

INSERT INTO #Test (Name, Rate, Principal)
VALUES  ('A', 0.5, 10),('B', 0, 10);


WITH Years AS (
 SELECT 1 Year
 UNION ALL 
 SELECT Year+1 FROM Years
 WHERE Year < 5
)
SELECT
     *
       FROM 
    (SELECT 'Year'+CAST(Year AS VARCHAR(1)) Year, 
        Name, 
        Rate, 
        Principal,   
        Principal * POWER((Rate+1), Year) Result
    FROM Years, #Test) A
PIVOT (MAX(RESULT) FOR YEAR IN ([Year1], [Year2], [Year3],[Year4],[Year5])) PVT


Name Rate                  Principal             Year1                 Year2                 Year3                 Year4                 Year5
---- --------------------- --------------------- --------------------- --------------------- --------------------- --------------------- ---------------------
A    0.50                  10.00                 15.00                 22.50                 33.75                 50.625                75.938
B    0.00                  10.00                 10.00                 10.00                 10.00                 10.00                 10.00