Recursive CTE Exponential Moving Average
Compute an exponential moving average with a recursive CTE joining each row to the previous smoothed value; window functions cannot reference their output.
Code
CREATE TABLE readings (
taken_at timestamptz NOT NULL,
value numeric NOT NULL
);
INSERT INTO readings VALUES
('2026-01-01 10:00', 10),
('2026-01-01 11:00', 4),
('2026-01-01 12:00', 6),
('2026-01-01 13:00', 2),
('2026-01-01 14:00', 8);
-- 窗口函数引用不了自己的输出,EMA 这类逐行递推改用递归 CTE
WITH RECURSIVE ordered AS (
SELECT taken_at, value, ROW_NUMBER() OVER (ORDER BY taken_at) AS rn
FROM readings
),
smoothed AS (
SELECT taken_at, value, value::numeric AS ema, rn
FROM ordered
WHERE rn = 1
UNION ALL
SELECT o.taken_at, o.value, 0.5 * o.value + 0.5 * e.ema, o.rn
FROM ordered o
JOIN smoothed e ON o.rn = e.rn + 1
)
SELECT taken_at, value, ROUND(ema, 3) AS ema
FROM smoothed
ORDER BY rn;
-- 首两行可手推:ema(2) = 0.5*4 + 0.5*10 = 7How it works
SELECT / INSERT / CREATE statements share the script, touching readings, ordered and smoothed.
In terms of clauses, the statements use: a CTE (WITH … AS) that names an intermediate result before the main query; one JOIN combining rows across tables; a WHERE clause that picks out the rows one statement touches; a window function (OVER (…)) calculating values across rows while every row stays visible; an ORDER BY that fixes the output order; a UNION that merges result sets from separate queries; NOT NULL qualifiers on the required columns.
Watch out for
- 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.
Applying it
Point it at the readings table.
Statements that matter
INSERT INTO readings VALUES
('2026-01-01 10:00', 10),
('2026-01-01 11:00', 4),
('2026-01-01 12:00', 6),
('2026-01-01 13:00', 2),
('2026-01-01 14:00', 8);
CREATE TABLE readings (
taken_at timestamptz NOT NULL,
value numeric NOT NULL
);
Interactive Tools for This Topic
FAQ
- Which tables does the SQL touch?
- `readings`, `ordered`, `smoothed`, combined through a join.
Report a problem with this exampleOpens a pre-filled issue on GitHub.