← Problems16. Running balance per accountMediumSQL
00:00 / 20:00

Running balance per account

Medium50% solve itAsked at Microsoft, PayPal

Return every transaction with the account balance after that transaction. Transactions are ordered by posted_at; when two share a timestamp, the lower txn_id posts first.

Input schema

transactions txn_id bigint account_id bigint posted_at timestamp amount numeric -- negative for debits

Constraints

  • Output all input columns plus balance
  • Order by account_id, then posted_at, then txn_id
  • An account's balance starts at zero

Example 1one account, three transactions

Input · transactions
amounttxn_idposted_ataccount_id
10012024-01-01 10:00:00500
-3022024-01-02 10:00:00500
20032024-01-03 10:00:00500
Output
txn_idaccount_idposted_atamountbalance
15002024-01-01 10:00:00100100
25002024-01-02 10:00:00-3070
35002024-01-03 10:00:00200270

Example 2balances do not leak between accounts

Input · transactions
amounttxn_idposted_ataccount_id
5012024-01-01 00:00:001
7022024-01-01 00:00:002
2532024-01-02 00:00:001
Output
txn_idaccount_idposted_atamountbalance
112024-01-01 00:00:005050
312024-01-02 00:00:002575
222024-01-01 00:00:007070

Topics

window functions

Similar problems

Community-reported interview topic. Not an official company question and no affiliation is implied.

solution.sql
Loading editor…
Draft not saved yet · Spaces 4 · UTF-8⌘↵ run ⌘⇧↵ submit
Nothing run yet

Run against the public tests, or submit to score against all of them.