Ranking & NTH Value SQL Topic exerciseHardVerified answerSQLite + PostgreSQL + MySQL + SQL Server live · 1 guided

Compute a Three-Run Moving Runtime Average

Calculate a three-run moving average per pipeline and round to two decimals.

  • Window functions
  • Aggregation
  • Numeric functions
  • Sorting

Exercise brief

Understand the request

Pipeline performance engineer Short-term runtime trend monitoring needs the current run and up to two immediate predecessors.

Short-term runtime trend monitoring needs the current run and up to two immediate predecessors. Calculate a three-run moving average per pipeline and round to two decimals.

Return

  • Return pipeline_name, run_id, started_at, duration_seconds, and rolling_3_run_avg.
  • Order by pipeline_name, started_at, and run_id.

Constraints

  • Use AVG as a window function.
  • Declare ROWS BETWEEN 2 PRECEDING AND CURRENT ROW.

Data you will use

Review the relevant tables before deciding how to join, filter, or aggregate them.

pipeline_runs

  • pipeline_nameTEXT
  • run_idINTEGER
  • started_atTEXT
  • duration_secondsINTEGER

Hints, when you need them

Open one clue at a time so you still do the reasoning.

Hint 1

A three-row moving window contains the current row plus two predecessors.

Hint 2

Use ROWS, not a value-based RANGE frame.

Hint 3

Order by started_at, run_id and round the AVG result.

Verified SQL answer

Attempt the problem first, then compare structure and reasoning—not just syntax.

Reveal solution and explanation
SELECT pipeline_name, run_id, started_at, duration_seconds, ROUND(AVG(duration_seconds) OVER (PARTITION BY pipeline_name ORDER BY started_at, run_id ROWS BETWEEN 2 PRECEDING AND CURRENT ROW), 2) AS rolling_3_run_avg FROM pipeline_runs ORDER BY pipeline_name, started_at, run_id;

Why this works

A bounded ROWS frame implements a physical rolling window and naturally uses fewer available rows at the beginning of each partition.

Success check

Early partitions use available rows and timestamp ties follow deterministic run_id order.

Expected result

Use this output to verify values, aliases, ordering, and row count.

pipeline_namerun_idstarted_atduration_secondsrolling_3_run_avg
billing_rollup3012026-06-03 08:00:00120120
billing_rollup3022026-06-03 09:00:00110115
billing_rollup3032026-06-03 10:00:0090106.67
billing_rollup3042026-06-03 11:00:009096.67
customer_sync2012026-06-03 09:30:003030
customer_sync2022026-06-03 10:30:003532.5
customer_sync2032026-06-03 11:30:003533.33
customer_sync2042026-06-03 12:30:002531.67
ingest_orders1012026-06-03 09:00:006060
ingest_orders1022026-06-03 10:00:004552.5

Previewing 10 of 12 expected rows. Run the query in the editor to inspect the full result.

Learn the concepts behind this answer

Strengthen your understanding with these targeted learning topics:

Continue practicing

SQL Practice Online

Open the interactive workspace and practice across SQL topics.