softwaretips4u Tips that Transform
← Back to Homepage ← Back to Articles

SQL Cumulative & Moving Aggregations (Running Totals & Rolling Averages)

🔹 Why These Aggregations Matter

Running totals and moving averages turn raw rows into trend insights. Whether you track revenue, conversions, or defect counts, window functions deliver progressive metrics without complicated self-joins.

⚙️ 1️⃣ Types of Window-Based Aggregations

TypeDescription
Cumulative TotalAdds values as the row order progresses.
Moving AverageReturns the average over the last N rows.
Cumulative Count / %Calculates progressive counts or ratios.

⚙️ 2️⃣ Sales Dataset

IDRegionMonthSales
1EastJan1000
2EastFeb1500
3EastMar1200
4EastApr1800
5WestJan2000
6WestFeb2500
7WestMar1800
8WestApr3000

⚙️ 3️⃣ Running Total per Region

SELECT 
  Region,
  Month,
  Sales,
  SUM(Sales) OVER (PARTITION BY Region ORDER BY Month) AS RunningTotal
FROM Sales;

⚙️ 4️⃣ Cumulative Count

SELECT 
  Region,
  Month,
  COUNT(*) OVER (PARTITION BY Region ORDER BY Month) AS MonthCount
FROM Sales;

⚙️ 5️⃣ Cumulative Percentage

SELECT 
  Region,
  Month,
  Sales,
  SUM(Sales) OVER (PARTITION BY Region ORDER BY Month) * 100.0 /
  SUM(Sales) OVER (PARTITION BY Region) AS CumulativePercent
FROM Sales;

⚙️ 6️⃣ 3-Month Moving Average

SELECT 
  Region,
  Month,
  Sales,
  AVG(Sales) OVER (
      PARTITION BY Region 
      ORDER BY Month 
      ROWS BETWEEN 2 PRECEDING AND CURRENT ROW
  ) AS MovingAvg3
FROM Sales;

⚙️ 7️⃣ Rolling Sum of Last Two Months

SELECT 
  Region,
  Month,
  Sales,
  SUM(Sales) OVER (
      PARTITION BY Region 
      ORDER BY Month 
      ROWS BETWEEN 1 PRECEDING AND CURRENT ROW
  ) AS TwoMonthSum
FROM Sales;

⚙️ 8️⃣ Running Totals with Dates

SELECT 
  Region,
  SaleDate,
  SUM(Sales) OVER (
      PARTITION BY Region
      ORDER BY SaleDate
  ) AS RunningTotal
FROM Sales;

🧩 Real-World Use Cases

Finance

Track revenue or expense growth over time using running totals.

Sales Dashboards

Visualize rolling averages to smooth out month-to-month spikes.

Web Analytics

Monitor cumulative sign-ups or conversions for campaigns.

Test Automation

Generate cumulative pass/fail counts directly in SQL for reports.

⚖️ Best Practices

💡 Interview Tip

“Running totals and moving averages rely on window frames. Explain how ROWS BETWEEN defines which rows feed each calculation.”
← Back to Articles | 🏠 Back to Homepage