案例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