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.

SqlData Integrity

Code

snippet
-- 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-level WHERE will not work — use an outer query or a CTE.

Using it

The growth table is the working surface here.

Interactive Tools for This Topic

FAQ

What objects does the SQL involve?
`growth`, `steps`.