Brightlane's finance team computes the cumulative revenue total as orders are processed in sequence by ID.
Write a query to return the ID and amount of every order, plus the running total of total_amount accumulated from the first order through that order in order of id.
Assumptions:
- The
orderstable has one row per order with anidand atotal_amount. - Orders are processed in ascending
idorder. The running total at each row is the combinedtotal_amountacross every order whoseidis less than or equal to that row'sid.
Output:
- One row per order, with columns
id,total_amount, andrunning_total.
Schema · ecommerce 5 tables
Run previews · Check grades
Write a query, then run it to see results here.
Worked solution Try it yourself first
SELECT
id,
total_amount,
SUM(total_amount) OVER (
ORDER BY
id
) AS running_total
FROM
orders The shape
SUM(total_amount) OVER (ORDER BY id) attaches a running total to every row. The OVER clause keeps each row in place; the ORDER BY id inside it tells PostgreSQL to accumulate total_amount from the first order through the current one. The cumulative revenue figure rides alongside the order, instead of collapsing the table into a single grand total.
Clause by clause
SELECT id, total_amountreturns each order's identifier and amount unchanged. The running total is computed alongside; the original rows are preserved.SUM(total_amount) OVER (ORDER BY id) AS running_totalis the window expression.SUMis the same aggregate used in aGROUP BY, but theOVERclause changes how it is applied. Instead of collapsing rows, it computes a value for each row using a set of related rows. TheORDER BY idinsideOVERdefines that set as every row with anidless than or equal to the current row, so the result accumulates asidadvances. On the first order,running_totalis129.98. On the second, it is129.98 + 999 = 1128.98. The growth continues to the last row.FROM ordersreads every order. There is noWHEREbecause the running total spans the whole table.
You practiced SUM(...) OVER (ORDER BY ...) — adding ORDER BY inside the window converts a partition-wide total into a running total accumulating as rows advance.