2014-03-06 95 views
0

我沒有看到我做錯了什麼。我在經常賬戶1000,從這個數額我想支付佣金一個接一個。最後一筆佣金必須保持不足以支付(20 + 1 + 1000) - 1000 = 2的金額。從表中減去金額

declare @CommissionTable table(AccountId INT, Amount DECIMAL(18,2)) 

INSERT INTO @CommissionTable VALUES(17584981,20) 
INSERT INTO @CommissionTable VALUES(17584982,1) 
INSERT INTO @CommissionTable VALUES(17584983,1000) 

DECLARE @CurrentAmount DECIMAL(18,2) 
SET @CurrentAmount = 1000 

declare @ComissToPay decimal(18,2) 

;WITH [comis] AS (SELECT Amount FROM @CommissionTable) 
UPDATE [comis] set @ComissToPay = CASE           

WHEN @CurrentAmount < CM.Amount THEN @CurrentAmount 

WHEN @CurrentAmount > CM.Amount THEN CM.Amount 
END, 

Amount = CM.Amount - isnull(@ComissToPay,0), 
@CurrentAmount = @CurrentAmount - isnull(@ComissToPay,0) 
from [comis] CM        

SELECT * FROM @CommissionTable 
+2

(20 + 1 + 1000) - 1000 = 2你怎麼得到2? –

+0

偶然得到21分嗎? – thepirat000

+0

我想在這裏幫助你,但我不確定你要找的最終結果是什麼樣子。你能發表你想看到的嗎? –

回答

0

你不能像你想要的那樣使用遞歸CTE。你將有更好的運氣,在這種情況下,光標,我想:

DECLARE @CommissionTable TABLE(AccountId INT, Amount DECIMAL(18,2)) 

INSERT INTO @CommissionTable VALUES(17584981,20) 
INSERT INTO @CommissionTable VALUES(17584982,1) 
INSERT INTO @CommissionTable VALUES(17584983,1000) 

DECLARE @CurrentAmount DECIMAL(18,2) 
SET @CurrentAmount = 1000 

DECLARE @thisID INT, @thisAmount DECIMAL(18,2), @ComissToPay DECIMAL(18,2) 

DECLARE db_cursor CURSOR FOR 
SELECT * 
FROM @CommissionTable 
ORDER BY Amount ASC 

OPEN db_cursor 
FETCH NEXT FROM db_cursor INTO @thisID, @thisAmount 

WHILE @@FETCH_STATUS = 0 AND @CurrentAmount > 0 
BEGIN 
    IF @thisAmount > @CurrentAmount 
     @ComissToPay = @CurrentAmount 
    ELSE 
     @ComissToPay = @thisAmount 

    UPDATE @CommissionTable SET Amount = Amount - @ComissToPay WHERE AccountID = @thisID 
    SET @CurrentAmount = @CurrentAmount - @ComissToPay 

    FETCH NEXT FROM db_cursor INTO @thisID, @thisAmount 
END 

CLOSE db_cursor 
DEALLOCATE db_cursor 

SELECT * FROM @CommissionTable 
PRINT 'Amount left over: ' + CAST(@CurrentAmount AS VARCHAR(50)) 

此代碼是未經測試的,因爲我從我目前不在辦公室,所以它可能包含一些小的語法錯誤,但希望這足以讓你走上正軌。

另請注意我添加的ORDER BY子句;我把你的佣金從最小到最大分類,這樣你可以在你開始試圖償還大錢之前,讓小孩們得到回報。

+0

是的,結果是正確的,非常感謝! – user3083705