我想使用sql创建一个表来复合兴趣。
name rate principal year1 year2
A .5 10 15 22.5
B .0 10 10 10.0
我能够为每个名称创建一个存储过程并对其进行硬编码两年,但这意味着每增加一年我就要再添加一年。是否有一种优雅而有效的方法,可以使用过程或仅查看视图?
答案 0 :(得分:1)
您似乎需要复利计算和支点。这是一个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
答案 1 :(得分:-2)
低于你想要的?
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