我正在寻找一个简单的递归公式的SQL Server解决方案。在示例中,X是我的数字列,Y是我尝试使用SQL查询创建的列。
我有一个数字列表,表示为X,并希望产生一种特殊的运行总和,不允许小于0,表示为Y.
基础案例
Y 1 = MAX(X 1 ,0)
递归规则
Y i = MAX(X i + Y i-1 ,0)
实施例
id X(Input) Y(Output)
1 15 15
2 -87 0
3 26 26
4 -87 0
5 4 4
6 -19 0
7 34 34
8 -4 30
9 40 70
10 -14 56
答案 0 :(得分:1)
假设您有一个id
列指定了排序,我很确定您必须使用递归CTE执行此操作。问题是"将负数设置为零"使情况复杂化。
我假设id
标识了排序。
with t as (
select t.*, row_number() over (order by id) as seqnum
from table t
),
cte as (
select X,
(case when X < 0 then 0 else X end) as Y
from t
where id = 1
union all
select tnext.X,
(case when tnext.X + cte.Y < 0 then 0 else tnext.X + cte.Y end) as Y
from cte join
t tnext
on t.id + 1 = tnext.id
)
select *
from cte;
答案 1 :(得分:0)
使用游标和表变量来捕获计算值可能有助于提高性能。
declare @T table
(
id int,
X int,
Y int
);
declare @id int;
declare @X int;
declare @Y int;
set @Y = 0;
declare C cursor local static forward_only read_only for
select T.id, T.X
from T
order by T.id;
open C;
fetch next from C into @id, @X;
while @@fetch_status = 0
begin
set @Y = case when @X + @Y < 0 then 0 else @X + @Y end;
insert into @T(id, X, Y) values (@id, @X, @Y);
fetch next from C into @id, @X;
end
close C;
deallocate C;
select T.id, T.X, T.Y
from @T as T
order by T.id;
按Best approaches for running totals
查看Aaron Bertrand