2016-11-14 59 views
0

我擁有以下客戶表,其中包含列ID,名稱和餘額。將餘額分配給餘額列的不同實例

我有量分配到每一行,直到量變爲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<[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)):

 
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;