Calculating running totals and moving averages

Time Series Analysis in SQL Server

Maham Faisal Khan

Senior Data Science Content Developer

Calculating running totals

Team Game RunsScored
AZ 1 8
AZ 2 6
AZ 3 3
FLA 1 7
FLA 2 7
FLA 3 6
Team Game RunsScored TotalRuns
AZ 1 8 8
AZ 2 6 14
AZ 3 3 17
FLA 1 7 7
FLA 2 7 14
FLA 3 6 20
Time Series Analysis in SQL Server

Running totals

SELECT
    s.Team,
    s.Game,
    s.RunsScored,
    SUM(s.RunsScored) OVER (
        PARTITION BY s.Team
        ORDER BY s.Game ASC
        RANGE BETWEEN
              UNBOUNDED PRECEDING
              AND CURRENT ROW
    ) AS TotalRuns
FROM #Scores s;
  • Team, Game, RunsScored columns
  • SUM(s.RunsScored)
  • OVER()
  • PARTITION BY s.Team
  • ORDER BY s.Game ASC
  • RANGE BETWEEN
  • UNBOUNDED PRECEDING
  • AND CURRENT ROW
Time Series Analysis in SQL Server

RANGE and ROWS

RANGE

  • Specify a range of results
  • "Duplicates" processed all at once
  • Only supports UNBOUNDED and CURRENT ROW

ROWS

  • Specify number of rows to include
  • "Duplicates" processed a row at a time
  • Supports UNBOUNDED, CURRENT ROW, and number of rows
Time Series Analysis in SQL Server

Calculating moving averages

SELECT
    s.Team,
    s.Game,
    s.RunsScored,
    AVG(s.RunsScored) OVER (
        PARTITION BY s.Team
        ORDER BY s.Game ASC
        ROWS BETWEEN 1 PRECEDING
            AND CURRENT ROW
    ) AS AvgRuns
FROM #Scores s;
Team Game RunsScored AvgRuns
AZ 1 8 8
AZ 2 6 7
AZ 3 3 4
FLA 1 7 7
FLA 2 7 7
FLA 3 6 6
Time Series Analysis in SQL Server

Let's practice!

Time Series Analysis in SQL Server

Preparing Video For Download...