Interview Questions/SQL/Rolling 3-Month Average Revenue

Rolling 3-Month Average Revenue

Preview mode. Log in to edit, run, submit, and save progress.

Medium

Description

You are given a MonthlyRevenue table with one row per month. Write a SQL query to compute for each month: the revenue for that month and the rolling 3-month average (the average of the current month and the two preceding months). For the first month, the average is just that month. For the second month, the average is over 2 months. Round the rolling average to 2 decimal places. Return the result ordered by month. Table: MonthlyRevenue

Column NameTypeDescription
monthVARCHARMonth in YYYY-MM format
revenueDECIMALTotal revenue for that month

Database Schema (Inferred)

MonthlyRevenue

Column NameExample Value
month2023-01
revenue1000

Example

MonthlyRevenue

monthrevenue
2023-011000
2023-021200
2023-03900
2023-041500
2023-051100
2023-061300

Output

monthrevenuerolling_3mo_avg
2023-0110001000
2023-0212001100
2023-039001033.33
2023-0415001200
2023-0511001166.67
2023-0613001300

Explanation:

Jan: only 1 row → avg 1000. Feb: (1000+1200)/2 = 1100. Mar: (1000+1200+900)/3 = 1033.33. Apr: (1200+900+1500)/3 = 1200. Each subsequent month uses the current + 2 preceding.

Approach hint

Start with a simple approach, explain the trade-off, then move toward a cleaner or more scalable solution.

Common mistake

Skipping assumptions, edge cases, or trade-offs can make an otherwise good answer feel incomplete.

SQL Editor
Loading...

MonthlyRevenue

monthrevenue
2023-011000
2023-021200
2023-03900
2023-041500
2023-051100
2023-061300

Output

monthrevenuerolling_3mo_avg
2023-0110001000
2023-0212001100
2023-039001033.33
2023-0415001200
2023-0511001166.67
2023-0613001300