我想使用第一行的值并在第二行的计算中使用它。我想在下一行使用第二行的caulculation结果。等等。
第1行:0 +输入 - 输出=结束
第2行:结束(第1行)+进 - 出=结束
第3行:结束(第2行)+进 - 出=结束
第4行:结束(第3行)+进 - 出=结束
我想计算开始和结束。我想知道你将如何解决这个问题。
答案 0 :(得分:1)
假设您要计算的值为start
和end
,那么您只需使用累计总和:
select in, out,
sum(in - out) over (order by id) - (in - out) as starting
sum(in - out) over (order by id) as ending
from t;
您还可以使用窗口farme来表达starting
:
select in, out,
sum(in - out) over (order by id rows between unbounded preceding and 1 preceding) as starting
sum(in - out) over (order by id) as ending
from t;
但是,这会为第一行返回NULL
值,第一个版本更容易输入。
答案 1 :(得分:0)
自SQL Sever 2012以来,您可以这样做。
SELECT SUM(In - Out) OVER(ORDER BY RowId ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW) AS End
FROM Table
要获得所需的确切解决方案,您可以执行以下操作: -
SELECT Row, In, Out, End,
SUM(End - (In - Out)) OVER(ORDER BY id ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW) AS Start
FROM ( SELECT Row,
In, Out,
SUM(In - Out) OVER(ORDER BY Row ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW) AS End
FROM Table) R
对于旧版本,您需要自行加入。