SQL Practice Logo

SQLPractice Online

Running Totals & Moving Averages: Concept

Module: Window Functions

Think of running totals and moving averages as two different ways to tell the story of your data over time. Running totals are like your bank account balance - they keep adding up everything that happened before to show you where you stand today. Moving averages are like the weather forecast - they smooth out the daily ups and downs to show you the underlying trend. Running totals answer "How much total progress have we made?" while moving averages answer "What direction are we heading?" Both are essential for turning raw daily numbers into business insights that executives can understand and act upon.

**

**Running Totals (Cumulative Sums) - The Progress Tracker:**

Running totals accumulate values from the beginning of the dataset (or partition) up to the current row. They're perfect for tracking cumulative progress.

```sql

-- Basic running total

SELECT

order_date,

daily_revenue,

SUM(daily_revenue) OVER (ORDER BY order_date) as running_total

FROM daily_sales

ORDER BY order_date;

-- Result shows cumulative revenue growth over time

-- Day 1: $1000 (total: $1000)

-- Day 2: $1200 (total: $2200)

-- Day 3: $800 (total: $3000)

```

**Running Total Use Cases:**

- ✅ **Financial reporting**: YTD revenue, QTD sales, cumulative profit

- ✅ **Goal tracking**: Progress toward annual targets, milestone tracking

- ✅ **Inventory management**: Cumulative stock movements, running balances

- ✅ **Performance metrics**: Cumulative customer acquisitions, total orders

**Moving Averages - The Trend Smoother:**

Moving averages calculate the average of values within a sliding window, smoothing out short-term fluctuations to reveal underlying trends.

```sql

-- 7-day moving average

SELECT

date,

daily_sales,

AVG(daily_sales) OVER (

ORDER BY date

ROWS BETWEEN 6 PRECEDING AND CURRENT ROW

) as seven_day_moving_avg

FROM daily_sales

ORDER BY date;

-- Smooths out daily volatility to show weekly trends

```

**Moving Average Use Cases:**

- ✅ **Trend analysis**: Stock price trends, sales patterns, user engagement

- ✅ **Forecasting**: Demand planning, capacity planning, budget forecasting