cswork / libraryOpen practice workspace

Coding questions · Fetch Rewards

Compute a Seven-Day Rolling Average

This question evaluates proficiency with time-series aggregation and windowing concepts, specifically computing calendar-based 7-day rolling averages for a daily metric and using SQL window functions while handling missing dates.

You are analyzing daily product metrics for the Fetch mobile app.

Table

daily_metric_values

ColumnTypeDescription
metric_dateDATECalendar date in the America/Chicago timezone. There is at most one row per metric_name per date. Some dates may be missing.
metric_nameVARCHARName of the metric, such as daily_active_users, purchases, or revenue.
metric_valueNUMERICValue of the metric on that date.

Task

For the metric named 'daily_active_users', compute the 7-day rolling average of metric_value for each available metric_date.

Requirements

  • The 7-day window should include the current date and the previous 6 calendar days.
  • The calculation should be based on calendar-day distance, not row count, because some dates may be missing.
  • Use SQL window functions.
  • Return one row per available metric_date for 'daily_active_users'.

Expected output columns

ColumnDescription
metric_dateThe date of the metric.
metric_valueThe metric value on that date.
rolling_7d_avgThe average metric value from metric_date - 6 days through metric_date, inclusive.

Compute a Seven-Day Rolling Average

Table daily_metric_values

columntypeconstraints
metric_dateDATE
metric_nameVARCHAR
metric_valueNUMERIC

Sample data:

metric_datemetric_namemetric_value
2023-07-01daily_active_users1000
2023-07-02daily_active_users1200
2023-07-04daily_active_users1300
2023-07-05daily_active_users800
2023-07-06daily_active_users900
2023-07-08daily_active_users1100
2023-07-09daily_active_users1500
2023-07-10daily_active_users1400
2023-07-11daily_active_users1600
2023-07-12daily_active_users1700
2023-07-01purchases250
2023-07-02purchases280
2023-07-01revenue5320.75
2023-07-02revenue5800.4

Expected output

For each available metric_date where metric_name = 'daily_active_users', return the metric_value and the average of metric_value across the 7-day period from metric_date - 6 days through metric_date (inclusive). Missing calendar dates contribute no rows to the average.

metric_datemetric_valuerolling_7d_avg
2023-07-0110001000
2023-07-0212001100
2023-07-0413001166.67
2023-07-058001075
2023-07-069001040
2023-07-0811001060
2023-07-0915001120
2023-07-1014001166.67
2023-07-1116001216.67
2023-07-1217001366.67

Hints

  1. Filter to metric_name = 'daily_active_users' first so the window only considers that metric.
  2. Use a window frame based on calendar days, not row count: RANGE BETWEEN INTERVAL '6' DAY PRECEDING AND CURRENT ROW.
  3. Order the window by metric_date to define the rolling direction.
  4. Return only one row per available metric_date; missing dates are simply absent from the table and thus from the average.