我正在编写一个查询,它是SQL Server中存储过程的一部分。我需要在SQL Server中找到累积求和。
变量将保存一个整数值,例如100
。我们说
Declare @Variable int = 100
现在@NewVariable
将具有以下公式:
@NewVariable = @Variable * (1 - 0.005)
因此@NewVariable = 99.5
现在,@NewestVariable
将具有以下公式;
@NewestVariable = @NewVariable * (1 - 0.005)
因此@NewestVariable
的值为99.00
同样,这种计算将发生24次,所有结果将在结束时总和。
因此最终结果将是:100 + 99.5 +99.00 + .... ...
我尝试使用@Count Variable(DECLARE @COUNT INT = 24
)并使用While循环来实现所需的结果,但我不确定我是否正确?
请求帮助!
谢谢!
答案 0 :(得分:2)
您可以使用CTE执行以下操作:
declare @variable int = 100
;with cte as
(
select convert(numeric(8,2), @variable) as var, 1 as recCount
union all
select convert(numeric(8,2), @variable * (1 - recCount*0.005)) as var, recCount+1 as recCount
from cte
where recCount < 24
)
select sum(var) as total from cte
修改:根据@ peter.petrov的评论进行调整以解决舍入错误
如果您需要在计算前获取每行的值,请使用 this fiddle
答案 1 :(得分:1)
试试这段代码。
declare @Variable decimal(20,10);
set @Variable = 100;
declare @Sum decimal(20,10);
set @Sum = 0;
declare @cnt int;
set @cnt = 1;
while (@cnt <= 24)
begin
set @Sum = @Sum + @Variable;
set @Variable = @Variable * (1.0 - 0.005);
set @cnt = @cnt + 1;
end;
select @Sum;
答案 2 :(得分:1)
一个简单的答案就是这样
DECLARE @Variable INT = 100
SELECT @Variable
DECLARE @counter INT = 1
DECLARE @SumVariable NUMERIC(20,2) = @Variable
DECLARE @NewVariable NUMERIC(20,2) = @Variable
WHILE(@counter<24)
BEGIN
SET @NewVariable = @NewVariable * 0.995
SET @SumVariable = @SumVariable + @NewVariable
SET @counter = @counter+1
END
SELECT @SumVariable
答案 3 :(得分:1)
您还可以使用"quirky update"来避免while循环。如果您没有在中间结果中进行交互,只需修改最后一个代码行以仅选择max(total)
。
DECLARE @total DECIMAL(10,3) = 0.000
;WITH "data" AS
(
SELECT CAST( 100 AS DECIMAL(10,3)) AS id
UNION ALL
SELECT CAST( id * ( 1 - 0.005 ) AS DECIMAL(10,3)) FROM "data" WHERE id > 100 * (1 - 21 * 0.005)
)
SELECT
id, total = CAST( 0.000 AS DECIMAL(10,3))
INTO #temp
FROM
"data"
OPTION ( MAXRECURSION 23 );
UPDATE t SET @total = total = @total + id FROM #temp t
SELECT * FROM #temp
请参阅SQL-Fiddle进行测试。