请帮助!!!
如何按期间计算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 :(得分:0)
这未经过测试(我甚至不知道它是否在语法上正确,因为我是用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列。您也许可以使用日期列,但我个人只需添加一个标识列。