Interview Questions/SQL/Month-over-Month Revenue Growth

Month-over-Month Revenue Growth

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

Medium

Description

You are given a table of sales transactions. Each row has a sale date and a revenue amount. Write a SQL query to compute the total revenue for each month, the previous month's revenue (prev_revenue), and the month-over-month growth percentage defined as: mom_growth_pct = ROUND((total_revenue - prev_revenue) / prev_revenue * 100, 2) For the very first month, prev_revenue and mom_growth_pct should be NULL. Return month (as YYYY-MM), total_revenue, prev_revenue, and mom_growth_pct ordered by month. Table: Sales

Column NameTypeDescription
idINTPrimary key
sale_dateDATEDate of the sale
revenueINTRevenue for this sale

Database Schema (Inferred)

Sales

Column NameExample Value
id1
sale_date2023-01-10
revenue5000

Example

Sales

idsale_daterevenue
12023-01-105000
22023-01-253000
32023-02-059000
42023-02-201000
52023-03-1512000
62023-04-108000

Output

monthtotal_revenueprev_revenuemom_growth_pct
2023-018000NULLNULL
2023-0210000800025
2023-03120001000020
2023-04800012000-33.33

Explanation:

First group sales by month, then use LAG() window function to get the previous month's total, then compute the percentage change.

Approach hint

Start with the simplest clear approach, explain the trade-off, then move toward the cleaner answer.

Common mistake

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

SQL Editor
Loading...

Sales

idsale_daterevenue
12023-01-105000
22023-01-253000
32023-02-059000
42023-02-201000
52023-03-1512000
62023-04-108000

Output

monthtotal_revenueprev_revenuemom_growth_pct
2023-018000NULLNULL
2023-0210000800025
2023-03120001000020
2023-04800012000-33.33
Month-over-Month Revenue Growth Interview Question | Practice in IDE | Mockr