Write a SQL query to calculate a running total.

Instruction: In PostgreSQL transactions(date date NOT NULL, amount numeric NOT NULL), return one row per date with its daily amount and cumulative amount through that date. Explain how the query would differ for a running total after each transaction.

Context: This question examines the candidate's ability to use window functions to perform advanced calculations over a set of rows that are related to the current row.

Updated

Official answer

With only a date and an amount, define the result as one cumulative total per date. First aggregate transactions on the same date, then compute the running total. Assume both columns are non-NULL in PostgreSQL:

WITH daily AS (
  SELECT date AS transaction_date, SUM(amount) AS daily_amount
  FROM transactions
  GROUP BY date
)
SELECT transaction_date, daily_amount,
       SUM(daily_amount) OVER (
         ORDER BY transaction_date
         ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW
       ) AS running_amount
FROM daily
ORDER BY transaction_date;

Amounts 10 and 20 on January 1 and -5 on January 3 produce daily totals 30 and -5, and cumulative totals 30 and 25. Dates without transactions are omitted; a calendar table is needed to show those dates.

For a separate running value after every transaction, add a unique transaction ID and order by date and ID under a stated tie policy. Ordering only by a nonunique date does not establish a deterministic sequence among same-day transactions. Define missing-amount handling rather than silently treating unknown values as zero.

Related Questions