Dataford
Interview QuestionsInterview GuidesExperiencesMock InterviewsPricing
Get started

Running Totals With CTEs

MediumSQL · PostgreSQL00:00
Practice interviewer
In session
5 left
00:00

Your question is Running Totals With CTEs. Start with the requirements and the two tables on the right.

Run and submit as often as you like. When you're ready, talk me through your approach or go straight to the code.

You need to log in / sign up to run or submit.

Problem

Alpaca's brokerage ledger needs a chronological cash-balance view for each account. Write a PostgreSQL query that uses a CTE to aggregate settled cash movements by account and date, then uses a correlated subquery and window function to calculate running balances.

Requirements

  1. Include only settled movements from February 2025 and exclude movements for unknown accounts.
  2. Aggregate multiple movements on the same account and date into daily_net_change, treating NULL amounts as zero.
  3. Add each account's starting balance through a correlated subquery, then calculate running_cash_balance in date order for each account.
  4. Return results ordered by account_id and movement_date.

Schema

accounts
ColumnTypeDescription
account_idPKVARCHAR(20)Alpaca brokerage account identifier
initial_cash_balanceNUMERIC(12,2)Cash balance before the reporting period
cash_movements
ColumnTypeDescription
movement_idPKINTUnique cash movement identifier
account_idVARCHAR(20)Account associated with the movement
movement_dateDATESettlement date of the movement
amountNUMERIC(12,2)Signed cash movement amount
statusVARCHAR(20)Processing status of the movement
Tablesaccountscash_movements
Your solutionPostgreSQL
You need to log in / sign up to run or submit.
Run a query to see results