Tweets Rolling Average

ASKED IN INTERVIEW
4pts
Twitter

Problem Statement

Twitter wants to monitor user engagement by looking at their tweet frequency. Specifically, you need to calculate the 3-day rolling average of tweets for each user.

Write an SQL query to calculate the 3-day rolling average of tweets for each user_id and tweet_date.

Rules:

  • The rolling average for a given day is the average of tweets on that day and the previous two days (3 days total).
  • If a user has only one or two days of history, the average should be calculated based on the available data.
  • Output the user_id, tweet_date, and the rolling_avg rounded to 2 decimal places.
  • Results must be sorted by user_id in ascending order, then by tweet_date in ascending order.
Tests your understanding of
Window Functions, Rolling Average, Time Series and Analytics

Input Tables

tweets
user_id(INTEGER)tweet_date(DATE)tweet_count(INTEGER)
12022-06-012
12022-06-021
12022-06-033
12022-06-044
12022-06-055
22022-06-0110
22022-06-025
22022-06-030
22022-06-0410
22022-06-052
32022-06-011
32022-06-021
32022-06-037
42022-06-012
42022-06-024

Expected Output

user_id(INTEGER)tweet_date(DATE)rolling_avg(DECIMAL)
12022-06-012
12022-06-021.5
12022-06-032
12022-06-042.67
12022-06-054
22022-06-0110
22022-06-027.5
22022-06-035
22022-06-045
22022-06-054
32022-06-011
32022-06-021
32022-06-033
42022-06-012
42022-06-023

Tags

MediumASKED IN INTERVIEWWindow FunctionsRolling AverageTime SeriesAnalytics
15-20 min
52%

Hints