A database has a transactions
table with columns: account_id
, date
, transaction_value
(signed integer). Another table (account_value
) stores the current total value of each account, which is the sum of all transaction_value
s per account. It is updated with a trigger on the transactions
table (i.e., INSERTs, UPDATEs and DELETEs to transactions
fire the trigger to change the account_value
.)
A new requirement is to calculate the account's total transaction value only over the last 365 days. Only the current running total is required, not previous totals. This value will be requested often, almost as often as the account_value
.
How would you implement this "sliding window sum" efficiently? A new table is ok. Is there a way to avoid summing over a year's range every time?