KatInterview

Trailing Week Totals of Voice Assistant Replies per Device

SQL & DataModel answer
MediumModel answerSQL & Datasqlwindow-functionstime-series

Last 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:

ColumnMeaning
dateCalendar day of the activity
deviceDevice type (for example echo, dot)
answersNumber of answers the device gave that day

Sample data:

datedeviceanswers
2019-01-01echo10
2019-01-02echo20
2019-01-03echo30
2019-01-01dot10
2019-01-02dot15

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.