Trailing Week Totals of Voice Assistant Replies per Device
SQL & DataModel answerLast updated
Write a query that gives each device's total replies over the current day and the six days before it, handling duplicate rows and missing dates correctly.
Weekly engagement per device
A voice-assistant analytics team stores daily activity in a table called ANSWERS:
| Column | Meaning |
|---|---|
date | Calendar day of the activity |
device | Device type (for example echo, dot) |
answers | Number of answers the device gave that day |
Sample data:
| date | device | answers |
|---|---|---|
| 2019-01-01 | echo | 10 |
| 2019-01-02 | echo | 20 |
| 2019-01-03 | echo | 30 |
| 2019-01-01 | dot | 10 |
| 2019-01-02 | dot | 15 |
Task
Write a query that returns date, device and trailing_7d_answers. The last column is the sum of answers for that device over a 7-day window: the row's own date plus the 6 preceding calendar days. Order the result by date.
Points to address in your answer
- State how you interpret "7-day" and which assumptions you make about the data (several rows per device and day? missing days?).
- Explain what happens during a device's first six days of data.
- Give a version for a database engine that does not support interval-based window frames.
- Optionally, show an equivalent in pandas.
- Say what you would change if the team also wanted rows for days with no activity.
Hints
Hint 1
Decide first whether the window is defined by row count or by calendar dates. If a device skips a day, those two definitions give different totals.
Hint 2
Collapse the table to a single row per (date, device) with a GROUP BY before applying any window logic, then partition the window by device and order it by date.
Hint 3
A date-based frame (RANGE with a 6-day interval preceding) handles gaps. If the engine lacks it, join the table to itself on the same device with the other date between d - 6 days and d, and group.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Clarify first
Each of these questions changes the query:
- Meaning of "7-day". I use the current day plus the 6 previous calendar days, so the value for 2019-01-08 covers 01-02 to 01-08.
- Duplicates. Can a device have several rows on one date? If so, aggregate to one row per (date, device) first.
- Gaps. If
echohas no row on 01-04, a window of "6 rows back" reaches further than 7 calendar days. This is the main trap. - Output rows. I assume one output row per existing (date, device), not per calendar day.
Core idea
Partition by device, order by date, and sum over a frame defined by date values, not row positions:
RANGE BETWEEN INTERVAL '6' DAY PRECEDING AND CURRENT ROW
ROWS BETWEEN 6 PRECEDING AND CURRENT ROW is correct only if every device has exactly one row for every day. With gaps it silently covers more than a week.
SQL (PostgreSQL 11+, MySQL 8, Oracle, Snowflake)
WITH daily AS (
SELECT date, device, SUM(answers) AS answers
FROM answers
GROUP BY date, device
)
SELECT
date,
device,
SUM(answers) OVER (
PARTITION BY device
ORDER BY date
RANGE BETWEEN INTERVAL '6' DAY PRECEDING AND CURRENT ROW
) AS trailing_7d_answers
FROM daily
ORDER BY date, device;
In MySQL the frame is written INTERVAL 6 DAY PRECEDING.
Fallback without interval frames
SQL Server, Redshift and older engines can use a self-join with an explicit date predicate:
WITH daily AS (
SELECT date, device, SUM(answers) AS answers
FROM answers
GROUP BY date, device
)
SELECT a.date, a.device, SUM(b.answers) AS trailing_7d_answers
FROM daily a
JOIN daily b
ON b.device = a.device
AND b.date BETWEEN a.date - INTERVAL '6' DAY AND a.date
GROUP BY a.date, a.device
ORDER BY a.date, a.device;
Another route is to cross-join a calendar table with the list of devices, left-join the data and use COALESCE(answers, 0). Every device then has a row per day, so ROWS 6 PRECEDING becomes correct. Choose this if zero-activity days must appear in the output.
Result on the sample
| date | device | trailing_7d_answers |
|---|---|---|
| 2019-01-01 | dot | 10 |
| 2019-01-01 | echo | 10 |
| 2019-01-02 | dot | 25 |
| 2019-01-02 | echo | 30 |
| 2019-01-03 | echo | 60 |
Why it works
- For a row (d, device), the frame holds exactly the same-device rows whose date lies in [d - 6, d]. Its sum is by definition the 7-calendar-day trailing total.
- Pre-aggregation guarantees one row per (date, device), which avoids duplicate output rows.
- The self-join states the same date predicate explicitly, so it gives identical numbers.
Complexity
Let n be the row count after daily aggregation.
| Approach | Time | Space |
|---|---|---|
| Window function | O(n log n), dominated by sorting on (device, date); the sliding sum is linear | O(n) |
| Self-join | O(n * k) with k <= 7 matches per row, plus join overhead | O(n) |
| Calendar fill | O(D * days), which can far exceed n for sparse data | O(D * days) |
Edge cases
- Date gaps: handled by
RANGEand by the self-join;ROWSover-reaches. - First six days of a device: the result is a partial-window sum (see 01-01 above). If only full windows are wanted, filter with
date >= MIN(date) OVER (PARTITION BY device) + 6. Raise this as a product question rather than choosing silently. - NULL answers:
SUMignores NULLs, but returns NULL if all values in the window are NULL. Wrap withCOALESCE(..., 0)if needed. - Timestamps instead of dates: cast to
DATEbefore grouping, otherwise the interval is measured from the time of day. - Late-starting devices: partitioning keeps each device's window independent.
pandas equivalent
import pandas as pd
def trailing_7d_answers(df: pd.DataFrame) -> pd.DataFrame:
daily = (
df.assign(date=pd.to_datetime(df["date"]).dt.normalize())
.groupby(["device", "date"], as_index=False)["answers"]
.sum()
.sort_values(["device", "date"])
.reset_index(drop=True)
)
# '7D' is a time-based window (t - 7 days, t], i.e. t-6 .. t inclusive
daily["trailing_7d_answers"] = (
daily.groupby("device", group_keys=False)
.apply(lambda g: g.rolling("7D", on="date")["answers"].sum())
.astype("int64")
)
return (
daily[["date", "device", "trailing_7d_answers"]]
.sort_values(["date", "device"])
.reset_index(drop=True)
)
The string offset "7D" gives a time-based window, the pandas counterpart of SQL RANGE. Using rolling(7) would be the ROWS version and has the same gap bug.
Common mistakes
- Using
ROWS BETWEEN 6 PRECEDINGwithout checking for missing days. - Forgetting to partition by device, so devices leak into each other's totals.
- Skipping the pre-aggregation and emitting duplicate rows.
- Off-by-one windows:
INTERVAL '7' DAY PRECEDINGcovers 8 days. - Not saying what should happen in a device's first week.