cswork / libraryOpen practice workspace

Coding questions · Stripe

Find the Latest Balance for a Bank Account

Query the latest dated bank-account balance using both bank and account identifiers while handling records across months and years.

Write a PostgreSQL query that returns the latest reported balance for one bank account.

Tables

bank_balances(bank_name text, account_name text, start_date date, end_date date, balance numeric(18,2))

requested_account(bank_name text, account_name text) contains exactly one row.

Rules

  • Match both bank name and account name exactly. Account names are text identifiers and may contain leading zeros.
  • For this exercise, latest means greatest end_date; each bank/account pair has at most one row with a given end date.
  • Every field is non-null, and start_date <= end_date.
  • Records may span different months and years. Dates are typed dates, not strings to compare lexicographically.

Output

Return one column named balance for the latest matching record. If the requested account has no record, return no rows. The end-date definition and missing-account behavior are explicit exercise conventions.

Example

bank_balances:

bank_nameaccount_namestart_dateend_datebalance
Harbor0012342021-12-012021-12-31150.00
Harbor0012342019-05-012019-05-31200.00
Bay0012342022-01-012022-01-31300.00

requested_account: ('Harbor', '001234')

Expected output:

balance
150.00

Latest Reported Balance for a Bank Account

Table bank_balances

columntypeconstraints
bank_nameTEXTNOT NULL
account_nameTEXTNOT NULL
start_dateDATENOT NULL
end_dateDATENOT NULL
balanceNUMERIC(18,2)NOT NULL

Sample data:

account_namebalancebank_nameend_datestart_date
001234200Harbor2019-05-312019-05-01
001234175.25Harbor2021-02-282021-02-01
001234150Harbor2021-12-312021-12-01
0012341180.4Harbor2022-01-312021-11-15
001234300Bay2022-03-312022-03-01
1234999Harbor2022-06-302022-06-01
00123550Harbor2023-01-312023-01-01
0043212750.6Bay2020-07-312020-07-01

Table requested_account

columntypeconstraints
bank_nameTEXTNOT NULL
account_nameTEXTNOT NULL

Sample data:

account_namebank_name
001234Harbor

Expected output

balance
1180.4

Hints

  1. The requested account is identified by both bank_name and account_name; the same account_name can appear at another bank.
  2. Treat account_name as text: '001234' and '1234' are different accounts.
  3. Latest is defined by end_date, which is a date column, not by start_date.