Skip to content
Onsite

7-day moving average of daily sales

MediumP2Coding

Table daily_sales:

ColumnType
daydate (primary key)
amountint

Days without sales have no row. Return a 7-day moving average of amount for every calendar day from the first to the last day in the table.

  • A missing day counts as 0 sales.
  • For each day, average that day and the 6 days before it; at the start of the range use the days that exist (fewer than 7).
  • Round to 2 decimals.

Output columns: day, moving_avg. Order by day.

Schema

CREATE TABLE daily_sales (
  day date PRIMARY KEY,
  amount int NOT NULL
);

Example 1

Input
daily_sales: (2024-01-01, 10), (2024-01-03, 30)
Output
(2024-01-01, 10.00), (2024-01-02, 5.00), (2024-01-03, 13.33)
Why
January 2 has no row, so it counts as 0.

Constraints

  • PostgreSQL dialect.

Hints

PostgreSQL
Run checks the 3 visible tests, Submit all 6.