← Back to SQL, page 14

sql-0261 · Medium mid

Write a query that compares each month's revenue with the same month one year earlier.

Aggregate revenue per month, then LEFT JOIN the result to itself on the same month number one year earlier. LAG(revenue, 12) works only if every month is present, so the join on computed keys is safer when months can be missing.

Full answer
sql
WITH m(month, revenue) AS (VALUES ('2025-03', 100), ('2025-04', 80), ('2026-02', 90), ('2026-03', 130))
SELECT cur.month, cur.revenue, prev.revenue AS last_year,
       ROUND(100.0 * (cur.revenue - prev.revenue) / NULLIF(prev.revenue, 0), 1) AS yoy_pct
FROM m cur
LEFT JOIN m prev ON prev.month = printf('%04d', CAST(substr(cur.month, 1, 4) AS INTEGER) - 1) || substr(cur.month, 5)
WHERE cur.month >= '2026-01'
ORDER BY cur.month;
monthrevenuelast_yearyoy_pct
2026-0290NULLNULL
2026-0313010030.0

March 2026 compares with March 2025. February 2026 has no row a year earlier, so the LEFT JOIN keeps it with NULL rather than dropping it.

The LAG version is shorter but assumes exactly 12 rows per year in order. With a missing month, LAG(revenue, 12) silently compares with the wrong month:

sql
WITH m(month, revenue) AS (VALUES ('2025-03', 100), ('2025-04', 80), ('2026-02', 90), ('2026-03', 130))
SELECT month, revenue, LAG(revenue, 12) OVER (ORDER BY month) AS lag12 FROM m ORDER BY month;
monthrevenuelag12
2025-03100NULL
2025-0480NULL
2026-0290NULL
2026-03130NULL

Here only four months exist, so LAG finds nothing 12 rows back and returns NULL everywhere, including for March 2026, which does have a prior-year month. Fill the calendar first if you want to use LAG.

sql
WITH m(month, revenue) AS (VALUES ('2025-03', 100), ('2025-04', 80), ('2026-02', 90), ('2026-03', 130))
SELECT cur.month, cur.revenue, prev.revenue AS last_year,
       ROUND(100.0 * (cur.revenue - prev.revenue) / NULLIF(prev.revenue, 0), 1) AS yoy_pct
FROM m cur
LEFT JOIN m prev ON prev.month = printf('%04d', CAST(substr(cur.month, 1, 4) AS INTEGER) - 1) || substr(cur.month, 5)
WHERE cur.month >= '2026-01'
ORDER BY cur.month;

WITH m(month, revenue) AS (VALUES ('2025-03', 100), ('2025-04', 80), ('2026-02', 90), ('2026-03', 130))
SELECT month, revenue, LAG(revenue, 12) OVER (ORDER BY month) AS lag12 FROM m ORDER BY month;

Checked on SQLite 3.46.1, run twice with identical output.

Key points

  • Aggregate per month first
  • Join each month to the same month a year earlier
  • LEFT JOIN keeps months without history
  • LAG(x, 12) needs a complete month series

Common mistakes

  • Using LAG(12) on data with missing months
  • Dividing by a NULL or zero prior value without NULLIF

Follow-ups

  • How would you compute the growth percentage?
  • How would you handle a fiscal year starting in April?

Tips

  • Mention the missing-month risk