修改
表中的值可以是负数(对于提问时的疏忽感到抱歉)
在完成所有搜索工作后,我非常坚持以下内容:
我想根据初始值计算一个运行总计。例如:
我的表格如下:
Year Percent Constant
==== ===== ========
2000 1.40 100
2001 -1.08 100
2002 1.30 100
期望的结果将是:
Year Percent Constant RunningTotal
==== ====== ======== ============
2000 1.40 100 140
2001 -1.08 100 128.8
2002 1.30 100 167.44
取计算值1.40 * 100并将其乘以下一行的百分比,1.08,依此类推。
我正在使用Sql Server 2012.我已经研究过使用公用表表达式,但似乎无法得到正确的语法。
答案 0 :(得分:3)
在SQL Server 2012+中,您将使用累积总和:
select t.*,
(const * sum(1 + percent / 100) over (order by year)) as rolling_sum
from t
order by t.year;
编辑:
哎呀,我注意到你似乎真的想要一个累积的产品。假设percent
总是大于0,那么只需使用logs:
select t.*,
(const * exp(sum(log(1 + percent / 100)) over (order by year))) as rolling_product
from t
order by t.year;
答案 1 :(得分:2)
使用LEAD关键字
SELECT
Year
, Percent
, Constant
, Percent * Constant * (LEAD(Percent) OVER(ORDER BY Year)) as RunningTotal
FROMYourTable
这是来自MSSQL 2012的新关键字
答案 2 :(得分:2)
您可以使用递归CTE
完成此任务;WITH values_cte AS (
SELECT [Year]
,[Percent]
,[Constant]
,CASE WHEN [v].[Percent] < 0 THEN
[v].[Constant] - (([v].[Percent] + 1) * [v].[Constant])
ELSE
[v].[Percent] * [v].[Constant]
END
AS [RunningTotal]
FROM [#tmp_Values] v
WHERE [v].[Year] = 2000
UNION ALL
SELECT v2.[Year]
,v2.[Percent]
,v2.[Constant]
,CASE WHEN [v2].[Percent] < 0 THEN
[v].[RunningTotal] + (([v2].[Percent] + 1) * [v].[RunningTotal])
ELSE
[v2].[Percent] * [v].[RunningTotal]
END
AS [RunningTotal]
FROM values_cte v
INNER JOIN [#tmp_Values] v2 ON v2.[Year] = v.[Year] + 1
)
SELECT *
FROM [values_cte]