2016-11-14 26 views
0

私は、id、name、balanceのカラムを持つ次のCustomerテーブルを持っています。金額の異なるインスタンスに金額を振り分ける

量は、それが私はどちらかのループまたはカーソルを使用したくないこの

while(Amount>0) 
begin 
    amount=(Amount)-(select the balance of the row) 
    (select the balance column of the row)=0 
end 

ようなものだ0

なっまで私は、行のそれぞれに分配する金額を持っています。

更新クエリで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<[email protected] then 0 
     else Balance 
    end 
from person 
where Balance<[email protected] 

    select @temp 
+0

サンプルデータ予想結果 – Mansoor

+0

使用しているdbmsにタグを付けます。 (そのコードはANSI SQL準拠ではありません) – jarlh

+0

T-sqlを使用しています – mac

答えて

0

sum(balance) over(order by balance)で)実行されている総ビルド:total - balance < @amountが更新されなければならないすべての行

 
supplier balance total 
A   300  300 
B   500  800 
C   1200  2000 
D   1400  3400 

(これは上記の例では供給業者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;