所以有2個表,Transactions
與created_at
列和Transaction_associations
與amount
和remaining_balance
列等。我需要計算amount
列中的運行總和(總計),顯然按created_at
列排序。唯一的問題是,我需要獲得所有在之前創建的事務的SUM
當前正在計算的事務。我將需要在更新查詢內部選擇一個SELECT
a current_transactions
表以便獲得當前的created_at
日期。但我不能。我錯過了什麼嗎?這種方法有其他選擇嗎?SQLite選擇內更新
UPDATE Transaction_associations SET remaining_balance =
(
SELECT SUM (Transaction_associations.amount)
FROM Transactions
JOIN Transaction_associations ON Transactions.id = transaction_id
WHERE created_at <= current_transactions.created_at // here
)
WHERE id IN
(
SELECT id
FROM Transaction_associations
JOIN Transactions ON Transactions.id = transaction_id
WHERE created_at >= '2014-11-24'
)
編輯:,將實施例。
Transactions Transaction_associations
created_at amount remaining_balance
2014-02-01 100 100
2014-03-01 50 150
2014-04-01 205 355
後來編輯:對SQLFiddle使用添加完整的代碼。我把它換成Transaction_associations與SUM TA2,因爲它抱怨的misuse of aggregate: SUM()
DROP TABLE IF EXISTS Transactions;
DROP TABLE IF EXISTS Transaction_associations;
CREATE TABLE Transactions (id integer, created_at text);
CREATE TABLE Transaction_associations (id integer, amount integer, remaining_balance integer, transaction_id integer);
INSERT INTO Transactions VALUES (1,'2015');
INSERT INTO Transactions VALUES (2,'2014');
INSERT INTO Transactions VALUES (3,'2013');
INSERT INTO Transactions VALUES (4,'2012');
INSERT INTO Transactions VALUES (5,'2010');
INSERT INTO Transaction_associations VALUES (6, 100, 0, 1);
INSERT INTO Transaction_associations VALUES (7, 20, 0, 2);
INSERT INTO Transaction_associations VALUES (8, 3, 0, 3);
INSERT INTO Transaction_associations VALUES (9, 40, 0, 4);
INSERT INTO Transaction_associations VALUES (10, 500, 0, 5);
UPDATE Transaction_associations
SET remaining_balance =
(
SELECT SUM(TA2.amount)
FROM Transactions
JOIN Transaction_associations AS TA2 ON Transactions.id = TA2.transaction_id
WHERE created_at <= (SELECT created_at
FROM Transactions
WHERE id = TA2.transaction_id)
)
WHERE transaction_id IN
(
SELECT id
FROM Transactions
WHERE created_at >= '2013'
);
SELECT * from Transactions join Transaction_associations on Transactions.id = Transaction_associations.transaction_id;
這導致,這是錯誤的:
1 2015 6 100 663 1
2 2014 7 20 663 2
3 2013 8 3 663 3
4 2012 9 40 0 4
5 2010 10 500 0 5
結果應該是:
1 2015 6 100 663 1
2 2014 7 20 563 2
3 2013 8 3 543 3
4 2012 9 40 0 4
5 2010 10 500 0 5
因爲您正在更新其他表,因此沒有「當前事務」。添加一些示例數據以顯示您正在嘗試執行的操作。 –
好的,是的。這是關鍵,有什麼其他的選擇來實現這一點。我會用一個例子來更新。重點是計算剩餘的平衡。 –
這是什麼意思?這些表是1:1關係嗎? –