Rolling Average

SQL practice problem 55 of 67 · Window Functions · Medium · 25 coins for your first accepted solve

For every match, in id order, return id, duration_sec and avg_last3 — the average duration of this match and the two before it (fewer for the first matches), rounded to 1 decimal.

Sort by id.

Schema

CREATE TABLE players (
  id         INT PRIMARY KEY,
  name       TEXT NOT NULL,
  country    TEXT,            -- NULL = unknown
  level      INT NOT NULL,
  joined_on  DATE NOT NULL,
  mentor_id  INT              -- another player's id, or NULL
);

CREATE TABLE matches (
  id            INT PRIMARY KEY,
  winner_id     INT NOT NULL REFERENCES players(id),
  loser_id      INT NOT NULL REFERENCES players(id),
  played_at     DATE NOT NULL,
  duration_sec  INT NOT NULL
);

Write your query in the browser, run it on the sample data, then submit it against hidden test data.

Previous: Level Ranks · Next: Guild Elders · All problems