SQL 服务器按照从前到后的顺序从记录中减去一个值

SQL Server Subtract a value from records in the order of first to last

我有一个包含 2 列的 table 临时文件

create table temp
(
    id int identity(1,1),
    amount decimal(18,2)
)

示例数据插入如下

insert into temp(amount) 
values (100), (200), (500)

Table 看起来像

id amount
-----------
1  100
2  200
3  500

我想要实现的是,如果假设我们从 table 中扣除 150,那么扣除应该按照 Id 的顺序进行。即id 1的金额为0(100-150 =0,剩余为50)然后id 2的金额为150(之前扣除的余额50必须从200减去)

所以结果数据集应该是

id amount
---------
1  0
2  150
3  500

Window 对之前所有记录的累计求和,保存到cte 做别名:

create table #a(id int,amount int)

insert #a values(1,100),(2,200),(3,500)

select * from #a

declare @sub int=150
;with cte as
(
    select id,amount,isnull(sum(amount) over (order by id rows between unbounded preceding and 1 preceding),0) as prev_sum
    from #a
)
select *,case
            when @sub-prev_sum>amount then 0
            when @sub-prev_sum>0 then amount-(@sub-prev_sum)
            else amount
         end
from cte