We have a PL/SQL procedure that calculates account balance. There a two tables, accounts and transactions. Procedure goes through all accounts and for every account runs this query in parallel! (sum of + and - transactions from some date):
SELECT sum(claim) - sum(debt)
FROM transactions
WHERE account_id = :b3
AND currency_id = :b2
AND account_type = 2
AND date > :b1
There is more then million accounts and similar number of transactions so this pl/sql creates lot's of queries and takes lot's of cpu and time to finish (and kills the machine it is running on).
Is there a way to calculate this in one pass through transactions table (instead of million passes) by using sum with group by account_id and currency_id or by putting sum in associative array sum[account_id, currency_id] like you would do in awk? Will it be faster? Of course sums have to be inserted in balance table in the end.