samedi 16 janvier 2016

SQLite select inside of update

So there are 2 tables, Transactions with created_at column and Transaction_associations with amount and remaining_balance columns, among others. I need to calculate a running sum(total) on the amount column, sorted by the created_at column, obviously. The only problem is that I need to get the SUM of all transactions that are created before the current transaction that is being calculated. I would've needed a select inside the update query in order to SELECT a current_transactions table in order to get hold of the current created_at date. However I can't. Am I missing something? Are there alternatives to this method?

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'
)

Aucun commentaire:

Enregistrer un commentaire