Dataford
Interview QuestionsInterview GuidesExperiencesCoaching
New
Pricing
Get started
Dataford
Popular roles
Software EngineerData AnalystData ScientistData EngineerBusiness AnalystAI EngineerMachine Learning EngineerProduct Manager
Browse
Browse All RolesEvery role hub, from analyst to MLBrowse All CompaniesCompany-specific interview loopsAll Interview GuidesThe full guide library
Top questions by role
Software EngineerData AnalystData ScientistData EngineerBusiness AnalystAI EngineerMachine Learning EngineerProduct Manager
Top questions by skill
SQLPythonStatisticsMachine LearningA/B TestingSystem DesignGenerative AIProduct SenseMetricsBehavioral
Browse all questions →Try a mock interview
Experiences
Practice
Mock InterviewsTimed interview simulations with feedbackCoaching1:1 coaching with people at your target companiesSuccess PathYour 6-week structured planModulesCurated lessons by topicWebinarsTalks from ex-Big Tech data leadsPlaygroundA free-form scratch editor
Learn
BlogInterview strategy and career adviceTech Job Market ReportHiring trends across data and AI rolesFor UniversitiesDataford for career centersAbout DatafordWho we are and how we build
Pricing
Build my plan
Running Totals With CTEs
00:00
5 left

Running Totals With CTEs

MediumSQL · PostgreSQL

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
Interviewer

Your question is Running Totals With CTEs. Start with the requirements and the two tables in the Question tab.

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.
CodePostgreSQL
Sign up free to run your codeLog inLn 1
Run your query to see results here.