Running Product Via Exp Sum Log
Multiply a running series without a PRODUCT aggregate: take logs, sum them over the window frame, then exp the total back into a running product.
Code
-- running product via exp(sum(log)) trick:窗口里没有 PRODUCT 聚合
WITH growth(day, factor) AS (
VALUES
(1, 1.10::numeric),
(2, 0.90::numeric),
(3, 1.25::numeric),
(4, 1.00::numeric)
),
-- log domain:ln(x) turns multiply into add;先过滤非正数避免 ln 报错
steps AS (
SELECT
day,
factor,
ln(factor) AS log_factor
FROM growth
WHERE factor > 0
)
SELECT
day,
factor,
-- sum(ln) OVER running 累加对数,exp 还原成 running product
round(exp(sum(log_factor) OVER (ORDER BY day)), 4) AS running_product
FROM steps
ORDER BY day;How it works
At its core this is a single SELECT statement against growth and steps.
In terms of clauses, the statements use: a CTE (WITH … AS) that names an intermediate result before the main query; a WHERE clause constraining which rows the statement operates on; SUM aggregation; a window function (OVER (…)) aggregating over the window with every row kept in the result; an ORDER BY that fixes the output order.
What to watch 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.
Using it
The growth table is the working surface here.
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
- What objects does the SQL involve?
- `growth`, `steps`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.