案例1:更新只为一个帐户
,如果你想这对于只有一个帐户,您可以使用此:
declare @AccountID INT
set @AccountID = 9500
update Ledger
set GL_adjustmentAmount = GL_adjustmentAmount + (select SUM(a.GL_AdjustmentAmount)
from Adjustment a
where a.GL_AccountID = @AccountID)
where GL_AccountID = @AccountID
你要知道,在accountId
将不得不在这里指定。
案例2:如果您希望这对所有账户工作(应该&更可能是这种情况),那么你就需要一个更“广义”查询更新所有帐户的
那种东西:
update Ledger
set GL_AdjustmentAmount = ISNULL(GL_AdjustmentAmount,0) + ISNULL(collatedAdjustments.adjustment, 0)
from Ledger ledger
inner join
(select a.GL_AccountID,
SUM(a.GL_AdjustmentAmount) as Adjustment
from Adjustment adjustments
group by adjustments.GL_accountID) as collated
on ledger.GL_accountID = collated.GL_accountID
下面是一些你可以测试这个对一些样本数据:
CREATE TABLE Ledger(GL_AccountID int, GL_Amount int, GL_AdjustmentAmount int);
CREATE TABLE Adjustment(GL_AccountID int, GL_AdjustmentAmount int);
INSERT INTO Ledger(GL_AccountID,GL_Amount, GL_AdjustmentAmount) VALUES(9500, null, null);
INSERT INTO Ledger(GL_AccountID,GL_Amount, GL_AdjustmentAmount) VALUES(9600, null, null);
INSERT INTO Ledger(GL_AccountID,GL_Amount, GL_AdjustmentAmount) VALUES(9700, null, null);
INSERT INTO Ledger(GL_AccountID,GL_Amount, GL_AdjustmentAmount) VALUES(9800, null, null);
INSERT INTO Adjustment(GL_AccountID, GL_AdjustmentAmount) VALUES(9500, 289.84);
INSERT INTO Adjustment(GL_AccountID, GL_AdjustmentAmount) VALUES(9500, 9.63);
INSERT INTO Adjustment(GL_AccountID, GL_AdjustmentAmount) VALUES(9500, 13646.11);
INSERT INTO Adjustment(GL_AccountID, GL_AdjustmentAmount) VALUES(9500, 835.31);
INSERT INTO Adjustment(GL_AccountID, GL_AdjustmentAmount) VALUES(9500, -210);
INSERT INTO Adjustment(GL_AccountID, GL_AdjustmentAmount) VALUES(9500, -1019.02);
INSERT INTO Adjustment(GL_AccountID, GL_AdjustmentAmount) VALUES(9500, -200);
INSERT INTO Adjustment(GL_AccountID, GL_AdjustmentAmount) VALUES(9600, 29.84);
INSERT INTO Adjustment(GL_AccountID, GL_AdjustmentAmount) VALUES(9600, 29.63);
INSERT INTO Adjustment(GL_AccountID, GL_AdjustmentAmount) VALUES(9600, 16646.11);
INSERT INTO Adjustment(GL_AccountID, GL_AdjustmentAmount) VALUES(9600, 335.31);
INSERT INTO Adjustment(GL_AccountID, GL_AdjustmentAmount) VALUES(9600, -1210);
INSERT INTO Adjustment(GL_AccountID, GL_AdjustmentAmount) VALUES(9600, -2019.02);
INSERT INTO Adjustment(GL_AccountID, GL_AdjustmentAmount) VALUES(9600, -1200);
INSERT INTO Adjustment(GL_AccountID, GL_AdjustmentAmount) VALUES(9700, 2239.02);
INSERT INTO Adjustment(GL_AccountID, GL_AdjustmentAmount) VALUES(9700, 1400);
INSERT INTO Adjustment(GL_AccountID, GL_AdjustmentAmount) VALUES(9800, 4121.02);
INSERT INTO Adjustment(GL_AccountID, GL_AdjustmentAmount) VALUES(9800, 1234);
该查询还将以前的任何调整(在ledger
表中)也纳入公式中。
希望这有助于!
您的预期结果是什么?你是否想“总结”这些值? – sgeddes
您是否希望在记帐表中的所有调整总数中有记录?如果是这样,你想聚集在一个cte /子查询然后更新,否则,如果你想每调整一个记录,你需要'INSERT'而不是''UPDATE'。 –
我正在使用sql 2008.我想最初在总帐中拥有每个GL_adjustedamount,但我认为总和值将是BEST。 :) – Ace