Ideally for this you should have a unique TransactionDateTime column in the
table, but mostly people just have the TransactionDate so you then need to
bring a unique TransactionID column into play. This can be an autonumber as
its values are arbitrary. An updateable query using the DSum function would
then be:
SELECT TransactionDate, Deposit, Payment,
DSUM("Deposit", "Transactions","TransactionDate <=
" & FORMAT(Transactions.TransactionDate,"\#mm/dd/yyyy\#") &
" AND (TransactionID <= " & Transactions.TransactionID &
" OR TransactionDate <> " &
FORMAT(Transactions.TransactionDate,"\#mm/dd/yyyy\#") & ")") -
DSUM("Payment", "Transactions","TransactionDate <=
" & FORMAT(Transactions.TransactionDate,"\#mm/dd/yyyy\#") &
" AND (TransactionID <= " & Transactions.TransactionID &
" OR TransactionDate <> " &
FORMAT(Transactions.TransactionDate,"\#mm/dd/yyyy\#")& ")")
AS Balance
FROM Transactions
ORDER BY TransactionDate, TransactionID;
You can also have a non-updateable query entirely in SQL, this time in date
descending order. This should perform faster than one using the DSum
function so is better where the data does not need to be edited, e.g. as a
report's RecordSource:
SELECT TransactionDate, Deposit, Payment,
(SELECT SUM(Deposit)
FROM Transactions AS T2
WHERE T2.TransactionDate <= T1.TransactionDate
AND ( T2.TransactionID <= T1.TransactionID
OR T2.TransactionDate <> T1.TransactionDate)) -
(SELECT SUM(Payment)
FROM Transactions AS T2
WHERE T2.TransactionDate <= T1.TransactionDate
AND ( T2.TransactionID <= T1.TransactionID
OR T2.TransactionDate <> T1.TransactionDate))
AS Balance
FROM Transactions AS T1
ORDER BY TransactionDate DESC , TransactionID DESC;
Its very important that there should be no NULLs in the Deposit or Payment
columns, so in table design set their Required property to True (Yes) and
give them a DefaultValue property of 0 (zero). The TransactionDate column
must also be Required of course.
Ken Sheridan
Stafford, England