从表中逐一减少金额

时间:2014-03-06 22:50:08

标签: sql sql-server sql-server-2008

我看不出我做错了什么。我在当前帐户中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  

1 个答案:

答案 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子句;我将您的佣金从最小到最大排序,这样您就可以在开始尝试偿还大笔佣金之前获得小额付款。