我有以下带有列ID,名称和余额的Customer表。
我有足够的金额分配到每一行,直到金额变为0
它就像这样
while(Amount>0)
begin
amount=(Amount)-(select the balance of the row)
(select the balance column of the row)=0
end
我也不想使用循环或光标。
我在更新查询中使用了case
,但这也无效。
declare @temp decimal(18,4)=1000
update Customer
set @temp=case
when @temp>Balance then
@temp-Balance
else @temp
end,
Balance=case
when Balance<=@temp then 0
else Balance
end
from person
where Balance<=@temp
select @temp
答案 0 :(得分:0)
建立一个运行总计(sum(balance) over(order by balance)
):
supplier balance total A 300 300 B 500 800 C 1200 2000 D 1400 3400
必须更新total - balance < @amount
的所有行(这是上面示例中的供应商A,B和C)。 total <= @amount
减少为null的那些; total > @amount
(上例中的供应商C)最终与total - @amount
的差异。
update s
set balance = case when total <= @amount then 0 else total - @amount end
(
select
balance,
sum(balance) over (order by balance) as total
from suppliers
) s
where total - balance <= @amount;