Month-Over-Month Revenue Change
Medium
SQLLAGWindow
Problem
Schema: Revenue(month VARCHAR, total DECIMAL). One row per YYYY-MM.
Return month, total, prev_total, and pct_change = (total - prev) / prev * 100 rounded to 2 decimals. First row has NULL for prev and change.
Example 1
Input: (2025-01, 100) (2025-02, 120)
Output: (2025-02, 120, 100, 20.00)
Constraints
- Months are sortable as text (
YYYY-MMformat).
Approach — Core Patterns
This is a Core Patterns problem. The idea: pick the data structure best matched to the constraints and solve it in one clean pass. Work through the reference code below line by line, then re-derive it yourself in the editor — that's how the pattern sticks.
Complexity: see the walkthrough below.
Solution code
SQL
SELECT month, total,
LAG(total) OVER (ORDER BY month) AS prev_total,
ROUND(
(total - LAG(total) OVER (ORDER BY month)) * 100.0
/ NULLIF(LAG(total) OVER (ORDER BY month), 0),
2
) AS pct_change
FROM Revenue
ORDER BY month;
Practice it
Reading a solution isn't the same as being able to write it under pressure. Open this problem in the in-browser editor, hide the solution, and solve it from scratch — your code runs against real test cases instantly.
Solve Month-Over-Month Revenue Change interactively → ← All solutions