You are given account transactions and need to produce a row-by-row balance audit for each account. Write a PostgreSQL query that shows each transaction with the prior balance, the balance change from the previous row, and the running balance after the transaction. The logic must work across records in timestamp order, so this is a good test of how you handle row-dependent calculations.
account_id, transaction_id, transaction_ts, amount, prior_balance, balance_change, running_balance.account_id, then transaction_ts, then transaction_id, using transaction_id to break timestamp ties.amount as zero when calculating running_balance and balance_change.prior_balance and balance_change to NULL; otherwise calculate balance_change as prior_balance minus twice the non-NULL amount.| Column | Type | Description |
|---|---|---|
| transaction_idPK | INT | Primary key for the transaction |
| account_id | INT | Account identifier |
| transaction_ts | TIMESTAMP | Transaction timestamp used for sequencing |
| transaction_type | VARCHAR(20) | Transaction category such as deposit or withdrawal |
| amount | NUMERIC(12,2) | Signed amount applied to the account |
| note | TEXT | Optional note or reason for the transaction |