2014-03-02 141 views
0

請幫忙!!!計算期間之間的金額

如何按期計算PayedManualAmount,期限在支付之間。 所以在第二支付(325),我必須獲得5 在第三支付(500),我必須獲得7等..

if(OBJECT_ID('tempdb..#Amount') IS NOT NULL) 
    drop table #Amount 

create table #Amount 
(
    Date    smalldatetime, 
    Disbursement  decimal(18,2), 
    PayedManualAmount decimal(18,2), 
    ForPayAmount  decimal(18,2) 
) 


INSERT INTO #AmountForPay(Date,Disbursement,PayedManualAmount,ForPayAmount) 
VALUES 
('20121226', 675.00 ,NULL ,8.37), 
('20121226', NULL ,5.00 ,0.00), 
('20121227', NULL ,NULL ,0.00), 
('20121228', NULL ,NULL ,0.00), 
('20130323', NULL ,NULL ,0.00), 
('20130324', NULL ,NULL ,0.00), 
('20130325', NULL ,NULL ,0.00), 
('20130326', NULL ,NULL ,0.00), 
('20130327', 325.00 ,NULL ,4.03),--ForPayAmount = SUM(PayedManualAmount) between 2012-12-26 and 2013-03-26 = 5 
('20130328', NULL ,4  ,0.00), 
('20130329', NULL ,NULL ,0.00), 
('20140228', NULL ,3  ,0.00), 
('20140301', NULL ,NULL ,0.00), 
('20140302', 500.00 ,NULL ,6.20), --ForPayAmount = SUM(PayedManualAmount) between 2013-03-27 and 2014-03-01 = 7 
+0

您的問題需要審查。 「支付之間」沒有意義。你應該說「在a和b之間」。 「第二撥款(325)」中的325來自哪裏? ... – koriander

回答

0

這不是測試(I甚至不知道如果是語法正確的,因爲我寫出來SSMS),但這樣的事情應該工作:

DECLARE @LastProcessedID INT 
SELECT @LastProcessedID = 0 

WHILE 1 = 1 BEGIN 
    SELECT TOP 1 @CurrentID = ID 
    FROM #Amount 
    WHERE ID > @CurrentID 
    AND Disbursement IS NOT NULL 
    ORDER BY ID 

    IF @@RowCount = 0 BREAK; 

    UPDATE #Amount 
    SET ForPayAmount = (SELECT SUM(PayedManualAmount) 
         FROM #Amount 
         WHERE ID < @CurrentID 
         AND ID > @LastProcessedID) 
    WHERE ID = @CurrentID 

    SELECT @LastProcessedID = @CurrentID 
END 

請注意,您將需要一個ID列添加到您的臨時表。你也許可以使用你的日期列,但我個人只是添加一個標識列。

+0

非常感謝! ))) – user3083705

+0

沒問題。如果這能解決你的問題,你能否接受它作爲答案? – Dan