Skip to content
Quantoros

Return each 2026 month (YYYY-MM), its total transaction amount rounded to 2 decimals, and the percent change versus…

SQLLevel: IntermediateCore interview patterns

Return each 2026 month (YYYY-MM), its total transaction amount rounded to 2 decimals, and the percent change versus the prior month rounded to 1 decimal (NULL for the first month), in chronological order. LAG-based trend analysis is a staple of this round.

Table definitions (from the source exercise):

CREATE TABLE transactions(transaction_id INTEGER PRIMARY KEY, account_id INTEGER, transaction_date TEXT, amount REAL, merchant_category TEXT);
Hints
  • Distinguish a missing value from zero, an empty string and false.
  • Test comparison, aggregation and filtering on a tiny missing-value example.

Answer

Approach: CTE of monthly totals, then LAG(total) OVER (ORDER BY month) and (cur - prev) / prev * 100.

WITH monthly AS (
  SELECT DATE_FORMAT(transaction_date, '%Y-%m') AS m, SUM(amount) AS total
  FROM transactions
  GROUP BY m
)
SELECT m, ROUND(total, 2) AS total,
       ROUND(100.0 * (total - LAG(total) OVER (ORDER BY m))
             / LAG(total) OVER (ORDER BY m), 1) AS mom_pct
FROM monthly
ORDER BY m;

The source uses SQLite with a MySQL compatibility layer. Date and string functions are dialect dependent; the query is preserved as published.

Source and licence: SQL Practice Lab — Ebrahim Sharifi · MIT

Related questions