// window reference

SQL period over period with LAG

Aggregate to one row per period, apply LAG over the period ordering, and compute the ratio, the clean replacement for double self-joins on the fact table.

Catégorie
Fenêtre
Returns
numeric ratio
In this category
19 of 79

Syntaxe

SELECT ... FROM (SELECT period, SUM(x) AS v ... GROUP BY period) t | v / LAG(v) OVER (ORDER BY period) - 1

Prise en charge des moteurs

MoteurSupportNotes
SQL Server Oui Supported under this name.
PostgreSQL Oui Supported under this name.
MySQL Oui MySQL 8.0+
SQLite Oui SQLite 3.25+
Oracle Oui Supported under this name.

Exemples

PostgreSQL

WITH monthly AS (
  SELECT date_trunc('month', order_date) AS month, SUM(total) AS revenue
  FROM orders
  GROUP BY 1
)
SELECT month, revenue,
       LAG(revenue) OVER (ORDER BY month) AS prev_month,
       ROUND(100.0 * (revenue - LAG(revenue) OVER (ORDER BY month))
             / LAG(revenue) OVER (ORDER BY month), 1) AS mom_pct
FROM monthly
ORDER BY month;

Bon à savoir

  • LAG must run over period rows, not raw fact rows: LAG over the fact table mixes rows inside the same month and returns intra-month deltas, not MoM.
  • Gaps in periods break the arithmetic: LAG steps back one row, so a missing month makes 'previous' two months ago. Generate the period spine (calendar table or generate_series) and LEFT JOIN facts onto it first.
  • Integer division kills growth rates: with integer columns, v / LAG(v) truncates on SQL Server, PostgreSQL and SQLite (MySQL and Oracle return a decimal). Multiply by 100.0 or cast one side first.

Questions about Period Over Period Comparison

Why use LAG instead of a self-join for YoY?

A self-join needs date arithmetic to find 'same month last year' and scans the fact table twice or more. LAG over monthly aggregates reads each period once, and LAG(revenue, 12) over a month spine gives YoY in the same pass.

How do I handle months with no sales?

Include them in the spine (zero-fill) before LAG, otherwise LAG skips them and, with November missing, December is compared against October.

Browse every function in the SQL function reference, or see what the SQLly desktop app does for your database.

Cheat sheets for the engines that have it: SQL Server, PostgreSQL, MySQL, SQLite, Oracle.

// fewer lookups

Functions your engine actually has

SQLly's completion lists the built-in functions of the engine you're connected to, whether that's SQL Server, PostgreSQL, MySQL, SQLite or Oracle. Hover a function for help, and signature hints show each argument as you type.