Year Over Year Growth With Lag
Compare each month to the same month a year ago: LAG(revenue, 12) assumes a dense series, while a calendar self-join on month - interval stays sparse-safe.
Code
CREATE TABLE monthly_revenue (
month date PRIMARY KEY,
revenue numeric NOT NULL
);
INSERT INTO monthly_revenue VALUES
('2024-01-01', 120000),
('2024-02-01', 128000),
('2025-01-01', 141000),
('2025-02-01', 150000);
-- LAG(revenue, 12) 向前数 12 行:只有月序列完整时才恰好等于去年同月
-- 本示例只有 4 行,12 行之前不存在,因此全部返回 NULL(缺月即错位的警告)
SELECT
month,
revenue,
LAG(revenue, 12) OVER (ORDER BY month) AS same_month_last_year
FROM monthly_revenue
ORDER BY month;
-- 稀疏安全写法:按日历自联结,'2025-01' 精确匹配 '2024-01',缺月不串行
SELECT
cur.month,
cur.revenue,
prev.revenue AS last_year,
ROUND(100.0 * (cur.revenue - prev.revenue) / prev.revenue, 1) AS yoy_pct
FROM monthly_revenue cur
LEFT JOIN monthly_revenue prev
ON prev.month = cur.month - INTERVAL '1 year'
ORDER BY cur.month;How it works
The file runs SELECT / INSERT / CREATE statements, touching monthly_revenue.
In terms of clauses, the statements use: one JOIN combining rows across tables; a window function (OVER (…)) computing values across rows without collapsing them; an ORDER BY that fixes the output order; NOT NULL qualifiers on the required columns; a PRIMARY KEY that enforces row identity.
Points of care
- Window functions evaluate after
WHERE/GROUP BY, so filtering on their output in the same-levelWHEREwill not work — use an outer query or a CTE.
Putting it to use
The monthly_revenue table is the working surface here.
Core lines
SELECT
cur.month,
cur.revenue,
prev.revenue AS last_year,
ROUND(100.0 * (cur.revenue - prev.revenue) / prev.revenue, 1) AS yoy_pct
FROM monthly_revenue cur
LEFT JOIN monthly_revenue prev
ON prev.month = cur.month - INTERVAL '1 year'
ORDER BY cur.month;
SELECT
month,
revenue,
LAG(revenue, 12) OVER (ORDER BY month) AS same_month_last_year
FROM monthly_revenue
ORDER BY month;
INSERT INTO monthly_revenue VALUES
('2024-01-01', 120000),
('2024-02-01', 128000),
('2025-01-01', 141000),
('2025-02-01', 150000);
Interactive Tools for This Topic
PostgreSQL EXPLAIN AnalyzerAnalyze PostgreSQL EXPLAIN ANALYZE text or FORMAT JSON plans locally to flag Seq Scans, slow nodes, row misestimates, disk sorts, and index hints.SQL DDL to TypeScript ConverterConvert SQL CREATE TABLE DDL statements into strict TypeScript interfaces with nullable, array, enum, JSONB, and Date or ISO string column mappings.Multi-Mode Escape & Unescape CodecEscape and unescape strings safely across JSON, JavaScript, SQL single-quoted literals, POSIX shell single quotes, and RFC 4180 CSV cells in your browser.SQL FormatterReformat SQL by uppercasing reserved words and breaking lines before SELECT, FROM, WHERE, and other clauses.
FAQ
- Which tables appear in this script?
- `monthly_revenue`, combined through a join.
Report a problem with this exampleOpens a pre-filled issue on GitHub.