Like-for-Like Period Comparisons in SQL
Every finance dashboard eventually gets the same bug report: "Sales are down 45% this month!" It is the 14th. The query compared fourteen days of this month with all thirty-one days of the same month last year. A like f
Every finance dashboard eventually gets the same bug report: "Sales are down 45% this month!" It is the 14th. The query compared fourteen days of this month with all thirty-one days of the same month last year.
A like for like comparison in SQL means comparing windows that genuinely match: same length, same position in the calendar, same rules for what counts. This post walks through the patterns I reach for in PostgreSQL, plus a Django version, and the edge cases that break naive year over year SQL.
All examples assume a simple table:
CREATE TABLE sales (
id bigserial PRIMARY KEY,
order_date date NOT NULL,
amount numeric(12,2) NOT NULL
);
CREATE INDEX ON sales (order_date);
The three rules of like-for-like windows
-
Half-open ranges. Use
>= start AND < end. It works the same fordateandtimestampcolumns and never double-counts midnight. - Shift both ends. The comparison window is the current window moved back by one period, start and end, not "the whole previous month".
- Decide calendar edge cases explicitly. Leap days, month ends and weekday alignment each need a rule, and the rule should be written down where the next developer will find it.
Like for like comparison in SQL: month to date vs last year
Given an "as of" date (inclusive), compute four boundaries and aggregate both windows in one pass with FILTER:
WITH params AS (
SELECT DATE '2026-03-14' AS as_of
),
win AS (
SELECT
date_trunc('month', as_of::timestamp)::date AS cur_start,
as_of + 1 AS cur_end, -- exclusive
(date_trunc('month', as_of::timestamp) - interval '1 year')::date AS ly_start,
(as_of - interval '1 year')::date + 1 AS ly_end -- exclusive
FROM params
)
SELECT
SUM(s.amount) FILTER (WHERE s.order_date >= w.cur_start AND s.order_date < w.cur_end) AS current_sales,
SUM(s.amount) FILTER (WHERE s.order_date >= w.ly_start AND s.order_date < w.ly_end) AS last_year_sales
FROM sales s
CROSS JOIN win w
WHERE (s.order_date >= w.cur_start AND s.order_date < w.cur_end)
OR (s.order_date >= w.ly_start AND s.order_date < w.ly_end);
For an as-of date of 14 March 2026, this compares 1–14 March 2026 with 1–14 March 2025. The WHERE clause keeps the scan to the two windows, so the index on order_date stays useful.
date + integer returns a date in PostgreSQL, which keeps the exclusive end boundary clean.
Previous period, not just last year
"Previous period" for month to date is the same number of days at the start of the previous month, clamped to that month's length (the 31st of March has no partner in February):
SELECT
prev_start,
LEAST(prev_start + (as_of - cur_start) + 1,
(prev_start + interval '1 month')::date) AS prev_end -- exclusive
FROM (
SELECT DATE '2026-03-31' AS as_of,
DATE '2026-03-01' AS cur_start,
DATE '2026-02-01' AS prev_start
) p;
Here as_of - cur_start is an integer number of days, and LEAST stops the window at the end of February.
Leap days and month ends
PostgreSQL clamps when you subtract a year from 29 February: DATE '2028-02-29' - interval '1 year' gives 28 February 2027. With the query above, February 2028 to date on the 29th compares 29 days with 28 days last year, which is the honest answer: last February only had 28.
The opposite case needs a decision. On 28 February 2025, the last-year window ends on 28 February 2024 and skips the 29th. If your as-of date is the last day of the month, you usually want the whole month last year instead:
CASE
WHEN as_of = (date_trunc('month', as_of::timestamp) + interval '1 month' - interval '1 day')::date
THEN (date_trunc('month', as_of::timestamp) - interval '1 year' + interval '1 month')::date
ELSE (as_of - interval '1 year')::date + 1
END AS ly_end
Both behaviors are defensible. What is not defensible is leaving it to chance and getting different answers from different reports.
Year over year SQL for a monthly series
For a trend chart you want every month with its previous month and same month last year. The trap: LAG(sales, 12) counts rows, not months. If a month has no sales, there is no row, and the lag silently points at the wrong month. Build a calendar first with generate_series:
WITH months AS (
SELECT generate_series(DATE '2024-01-01', DATE '2026-12-01', interval '1 month')::date AS month
),
monthly AS (
SELECT m.month, COALESCE(SUM(s.amount), 0) AS sales
FROM months m
LEFT JOIN sales s
ON s.order_date >= m.month
AND s.order_date < m.month + interval '1 month'
GROUP BY m.month
)
SELECT
month,
sales,
LAG(sales, 1) OVER w AS prev_month,
LAG(sales, 12) OVER w AS same_month_last_year,
ROUND(100.0 * (sales - LAG(sales, 12) OVER w)
/ NULLIF(LAG(sales, 12) OVER w, 0), 1) AS yoy_pct,
(month + interval '1 month') > CURRENT_DATE AS is_partial
FROM monthly
WINDOW w AS (ORDER BY month)
ORDER BY month;
Three details matter here:
-
COALESCE(..., 0)turns empty months into real zeros, so the gap is visible instead of hidden. -
NULLIF(..., 0)avoids a division-by-zero error and returnsNULL(shown as "n/a"), which is more truthful than an infinite percentage. -
is_partialflags the current month. Either hide its percentage or switch that row to the month-to-date query above.
Weeks: compare 364 days back, not one year
Weekly sales depend heavily on the day of the week. Subtracting one calendar year shifts the weekday by one or two days, so a window of Monday to Sunday becomes Tuesday to Monday last year. Shift by 52 weeks (364 days) instead:
SELECT
SUM(amount) FILTER (WHERE order_date >= DATE '2026-03-09' AND order_date < DATE '2026-03-16') AS this_week,
SUM(amount) FILTER (WHERE order_date >= DATE '2026-03-09' - 364 AND order_date < DATE '2026-03-16' - 364) AS same_week_last_year
FROM sales
WHERE order_date >= DATE '2026-03-09' - 364;
The trade-off: 364 days back lands one or two calendar days earlier, so an event tied to a fixed date (a public holiday, say) can fall in a different week. Retail calendars handle the long-run drift by adding a 53rd week every five or six years. If your users run a 4-4-5 or similar calendar, store it in a table and join on it instead of computing dates.
The same logic in Django
In a Django app I keep window maths in Python, where it is easy to unit test, and let the database do one aggregate query. python-dateutil's relativedelta clamps 29 February the same way PostgreSQL does:
from datetime import date, timedelta
from dateutil.relativedelta import relativedelta
from django.db.models import Q, Sum
def mtd_vs_last_year(as_of: date) -> dict:
cur_start = as_of.replace(day=1)
cur_end = as_of + timedelta(days=1) # exclusive
ly_start = cur_start - relativedelta(years=1)
ly_end = as_of - relativedelta(years=1) + timedelta(days=1)
cur = Q(order_date__gte=cur_start, order_date__lt=cur_end)
ly = Q(order_date__gte=ly_start, order_date__lt=ly_end)
return Sale.objects.filter(cur | ly).aggregate(
current=Sum("amount", filter=cur),
last_year=Sum("amount", filter=ly),
)
Tests worth writing on day one: 1 January, the 31st of a month, 29 February, 28 February in the year after a leap year, and an as-of date with no sales at all (both sums come back as None, which your template should show as zero or "no data", deliberately).
Time zones: the quiet source of mismatches
If order_date is really a timestamptz, every window above depends on which time zone "the 14th" is in. A sale at 23:30 in New York is already the next day in UTC. Convert to the business's local zone before truncating, for example (created_at AT TIME ZONE 'America/New_York')::date, and store that zone per company rather than relying on the server or session setting. Otherwise your dashboard and the accounting system will disagree by a handful of late-evening sales every period, and nobody will be able to explain why.
Checklist before you ship a comparison
- Half-open ranges everywhere
- Both window ends shifted, not just the start
- A written rule for leap days and month ends
- A calendar table or
generate_seriesbefore anyLAG -
NULLIFon every denominator - Partial periods flagged in the API response, not guessed by the frontend
- Weekly comparisons aligned by weekday
- Dates converted to the business's time zone before truncating
How Lumetric approaches it
Lumetric, a read-only reporting dashboard over QuickBooks Online, Xero, Shopify and CSV/Excel uploads, shows each KPI next to the previous period and the same period last year, compared like for like, across week, month, quarter, year-to-date and year views. If you are building something similar, the patterns above are a solid starting point; if you would rather not build it, have a look.
See how Lumetric handles this: https://lumetric.example/?utm_source=devto&utm_medium=blog&utm_campaign=launch_m1&utm_content=d004-article
Originally published at Lumetric blog.
Originally published by Dev.to WebDev. Aggregated on AIWithGhost for educational purposes — full credit and traffic to the original publisher.