This guide is specifically for MySQL syntax.
How to SQL Query for Running Total in SQL
Calculate cumulative sum using window functions with SUM() OVER().
Quick Answer
SELECT date, amount, SUM(amount) OVER (ORDER BY date) as running_total FROM transactions;
Explanation
SUM() OVER() creates a running total. ORDER BY defines the accumulation order. PARTITION BY restarts the total for each group.
Query Variants
Basic
SELECT transaction_date, amount, SUM(amount) OVER (ORDER BY transaction_date) as running_total FROM transactions;
Partitioned
SELECT account_id, transaction_date, amount, SUM(amount) OVER (PARTITION BY account_id ORDER BY transaction_date) as account_balance FROM transactions;
Moving Average
SELECT date, value, AVG(value) OVER (ORDER BY date ROWS BETWEEN 6 PRECEDING AND CURRENT ROW) as moving_avg_7 FROM daily_stats;
Pro Tips
- PARTITION BY creates separate running totals per group
- Use ROWS BETWEEN for moving windows
- Available in most modern databases
Related SQL Queries
Continue learning with more SQL query examples:
MySQL-Specific Notes
This page covers MySQL syntax. Other databases may have different syntax for similar operations.