SQL Query

SQL Server: How to SQL Query for Running Total in SQL

SQL Server guide: Calculate cumulative sum using window functions with SUM() OVER().

This guide is specifically for SQL Server 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:


SQL Server-Specific Notes

This page covers SQL Server syntax. Other databases may have different syntax for similar operations.

Related Content

From Our Blog

Try it yourself

Practice this query in our interactive SQL sandbox.