使用 SQL 移动计算

Moving calculations using SQL

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

比如我有一个table:

A B
10 15
11 14
12 13

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

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

谢谢!

文档中有一条警告:

If there are multiple assignment clauses in a single SELECT statement, SQL Server does not guarantee the order of evaluation of the expressions. Note that effects are only visible if there are references among the assignments. It means there is no guarantee that it will evaluate the expression left-to-right. For this code:

declare @a int, @b int;
select @a = 2, @b = @a * 3;
select @a, @b;

结果可能是 2, 6(@a = ... 首先计算)或 2, NULL(@b = ... 首先计算)。

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