Timedora

Rolling Metrics and Time Windows in SQL

A practical guide to preparing time-series data and choosing SQL window frames for rolling metrics and period-over-period comparisons.

Set the and Prepare the Series

Set the and prepare the series

Before calculating daily metrics, decide which time zone defines a reporting day. A timestamp near midnight UTC may belong to a different local business date. In PostgreSQL, date_trunc can bucket timestamps to a chosen unit; for timestamp with time zone, its time-zone-aware form lets you specify the reporting zone. Assign timestamps to the intended business dates before aggregating. The source example assumes its order_date values already follow that calendar.

Next, aggregate records to the reporting grain—for example, one row per day—before applying a daily rolling calculation. If dates with no activity should count as zero-activity days, build a complete calendar and left join the daily records to it. Use COALESCE to turn the missing activity into zero. This choice affects averages: zero-activity dates are included in the average. If the intended average is only across active days, define that rule separately, such as by counting active days.

The source example reports January 1–10, 2026, and creates dates starting six days earlier. That lookback lets January 1 use the current date plus the six preceding dates for its seven-day window. Calculate the rolling results across this expanded series, then filter to the displayed report dates. Filtering first would leave the first reported dates without all the history needed for a complete window.

Choose a Frame and Calculate Rolling Metrics

Choose a frame and calculate rolling metrics

A window's ORDER BY establishes the sequence; its frame determines which contribute to each result. For a seven-row rolling metric, the source uses BETWEEN 6 PRECEDING AND CURRENT ROW: the current row and up to six earlier . The same explicit frame can be used with SUM, AVG, COUNT, MIN, or MAX.

The frame type must match the question. counts physical , so it means seven calendar days only if the input has exactly one row per calendar day. measures distance in the ordering value; in PostgreSQL, an offset frame for date or timestamp ordering uses an interval and requires a single ORDER BY expression. Equal ordering values are peers and can share a frame. GROUPS counts peer groups, not individual .

How window frame types differ
FrameWhat it counts or measuresQualification
ROWSPhysical rows in the ordered resultSeven rows equal seven calendar days only with one row per day.
RANGEDistance in the ordering valueOffset date/time frames use an interval and a single ORDER BY expression in PostgreSQL; equal values are peers.
GROUPSPeer groups of equal ordering valuesCounts groups rather than individual rows.
Frame types describe different ways to select rows relative to the current row; the appropriate choice depends on the intended window.

Apply an explicit rolling frame

In the source example, daily contains one row per calendar day, including dates with no orders. The rolling CTE can therefore use a seven-row frame to represent the current day and six previous days:

SELECT day,
       revenue,
       SUM(revenue) OVER (
           ORDER BY day
           ROWS BETWEEN 6 PRECEDING AND CURRENT ROW
       ) AS revenue_7d,
       AVG(revenue) OVER (
           ORDER BY day
           ROWS BETWEEN 6 PRECEDING AND CURRENT ROW
       ) AS avg_daily_revenue_7d,
       COUNT(*) OVER (
           ORDER BY day
           ROWS BETWEEN 6 PRECEDING AND CURRENT ROW
       ) AS days_in_frame
FROM daily;

For the first displayed date in the source example, the six lookback dates make the frame complete. Its sum is the seven daily revenues added together; its average is the sum divided across the days in the frame. The count helps show how many contribute. Because the series includes every date, a zero-activity date contributes a zero to the average as well.

Ordering must also identify the intended sequence. If multiple records share a date, aggregate to one row per date first when the goal is a daily metric. For a genuinely row-by-row calculation, add a unique tie-breaker if needed; without a unique ordering, results can be unpredictable.

Compare Each Period with Its Predecessor

Compare each period with its predecessor

Use with an ordering column to retrieve the previous row's value. For daily revenue, the source example uses:

SELECT day,
       revenue,
       LAG(revenue) OVER (ORDER BY day) AS previous_day_revenue
FROM daily;

To calculate percentage change, compare the current value with the previous value, subtract the previous value from the current value, divide by the previous value, and multiply by 100. A later query layer makes the result available for this calculation, since SQL generally does not allow one window function to use another window function's result directly in the same select-list expression. For example:

WITH with_previous AS (
    SELECT day,
           revenue,
           LAG(revenue) OVER (ORDER BY day) AS previous_day_revenue
    FROM daily
)
SELECT day,
       revenue,
       previous_day_revenue,
       (revenue - previous_day_revenue) * 100.0
           / NULLIF(previous_day_revenue, 0) AS percentage_change
FROM with_previous;

The result is expressed in percent units (for example, 25 represents a 25% change). (previous_day_revenue, 0) prevents division by zero when the previous value is zero. The first ordered row has no preceding row, so it has no previous value to compare against.

  • : The time interval represented by each row, such as one row per business date.