7-day moving average of daily sales
MediumP2Coding
Table daily_sales:
| Column | Type |
|---|---|
| day | date (primary key) |
| amount | int |
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
Give it a real attempt first. Run shows which examples fail.
Saved automatically
PostgreSQL
Run checks the 3 visible tests, Submit all 6. ⌘Enter runs, ⌘⇧Enter submits.