sql / intermediate
Snippet
Calculating Running Totals with Window Functions
Window functions perform calculations across a set of table rows related to the current row without collapsing the result set into a single row. The OVER clause combined with PARTITION BY and ORDER BY creates an aggregated running total per account over time.
snippet.sql
sql
1
2
3
4
5
6
7
8
9
10
SELECTtransaction_id,account_id,amount,SUM(amount) OVER (PARTITION BY account_idORDER BY transaction_dateROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW) AS running_balanceFROM transactions;
Breakdown
1
SUM(amount) OVER (
Initiates a windowed summation over a specified frame of rows.
2
PARTITION BY account_id
Resets the calculation boundary for each unique account identifier.
3
ORDER BY transaction_date
Sorts records chronologically to calculate the balance sequentially.
4
ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW
Defines the sliding frame from the first partition row up to the current record.