首页 > 解决方案 > 使用 SQL 移动计算

问题描述

我需要使用移动计算来计算一个新列。

例如,我有一张桌子:

一个
10 15
11 14
12 13

我需要计算第一个值计算的新列第二5000/10*15(5000 / 10 * 15) / 11 * 14第三个值是((5000 / 10 * 15) / 11 * 14) / 12 * 13等等其中 5000 是一个随机值,以后我会将它用作存储过程中的参数。

我知道,例如在 Excel 中,我们可以参考之前计算的单元格。如何使用 SQL 计算?

谢谢!

标签: sqlsql-serverwindow-functionscalculated-columnscalculation

解决方案


create table #test (A int,B int)

insert into #test values(10,15),(11,14),(12,13)

declare @seed int=5000;

;with temp as (
 select A,B,row_number() over(order by a) rn from #test
),
cte as
(
 select @seed/A*B  calculated,rn from temp where rn=1
 union all
 select c. calculated/t.A*t.B,t.rn from temp t
 join cte c on t.rn=c.rn+1
)
select * from cte

推荐阅读