// SQL snippet

Compare to the same day last year

A self-join on order_date minus one year puts the two years side by side.

Main statement
PostgreSQL
次もカバーします
SQL Server

The task

You want this year's daily revenue next to the same calendar day of last year, so you can spot real seasonality instead of week-to-week noise.

The snippet

Written for PostgreSQL. Versions for SQL Server are under Variations.

PostgreSQL
WITH daily AS (
  SELECT CAST(order_date AS date) AS day, SUM(amount) AS total
  FROM orders
  GROUP BY 1
)
SELECT d.day, d.total, y.total AS total_last_year,
       d.total - y.total AS change
FROM daily d
LEFT JOIN daily y
       ON y.day = d.day - INTERVAL '1 year'
WHERE d.day >= DATE '2026-01-01'
ORDER BY d.day;

仕組み

The CTE computes one total per day. Joining it to itself on day minus one year pairs each day with its counterpart from a year earlier; the LEFT JOIN keeps days that had no sales last year, which come back with NULL. The interval syntax is PostgreSQL; SQL Server uses DATEADD(year, -1, d.day) and MySQL uses DATE_SUB(d.day, INTERVAL 1 YEAR).

Variations

SQL Server: one year back with DATEADD

SQL Server
WITH daily AS (
  SELECT CAST(order_date AS date) AS day, SUM(amount) AS total
  FROM orders
  GROUP BY CAST(order_date AS date)
)
SELECT d.day, d.total, y.total AS total_last_year
FROM daily d
LEFT JOIN daily y
       ON y.day = DATEADD(year, -1, d.day)
WHERE d.day >= '2026-01-01'
ORDER BY d.day;

Same weekday last year (52 weeks back)

WITH daily AS (
  SELECT CAST(order_date AS date) AS day, SUM(amount) AS total
  FROM orders
  GROUP BY 1
)
SELECT d.day, d.total, y.total AS total_same_weekday
FROM daily d
LEFT JOIN daily y
       ON y.day = d.day - INTERVAL '364 days'
WHERE d.day >= DATE '2026-01-01'
ORDER BY d.day;

Questions that come up

What about February 29?

Both PostgreSQL (d.day - INTERVAL '1 year') and SQL Server (DATEADD(year, -1, ...)) clamp 2028-02-29 to 2027-02-28, so February 28 of last year is matched twice, once by the 28th and once by the 29th. If that double-counts in a summed report, exclude the leap day or map it to NULL explicitly.

Keep reading

// snippets are better with a schema brain

Run these with autocomplete that knows your tables

SQLly is a native SQL workbench for macOS, Windows and Linux. Paste a snippet into a live connection and you get schema-aware IntelliSense, a plan viewer and guards against unsafe edits.