2Recursive cumulative function - reuse resulting rows as inputRecursive cumulative function - reuse resulting rows as input

A window function does not operate recursively, and recursive CTEs don't allow aggregation in the recursive term.

Each result contributes to the next row recursively. This function writes to a temp table and reuses results:

```
CREATE OR REPLACE FUNCTION f_special_running_sum()
RETURNS TABLE(id int, result text)
LANGUAGE plpgsql AS
$func$
DECLARE
t record;
BEGIN
DROP TABLE IF EXISTS pg_temp.result;
CREATE TEMP TABLE result (id int, trx int, result float8) ON COMMIT DROP;
FOR t IN
TABLE tbl ORDER BY id -- your actual table name here!
LOOP
INSERT INTO result(id, trx, result)
SELECT t.id, t.trx
, (COALESCE(sum(r.trx + r.result), 0) + t.trx) * t.event
FROM result r;
END LOOP;
-- format output
RETURN QUERY
SELECT r.id, to_char(r.result, 'FM9999990.000000')
FROM result r;
END
$func$;
```

*db<>fiddle here*

Call:

```
SELECT * FROM f_special_running_sum();
```

I formatted the resulting number as text to match your desired result exactly. You may want a `numeric`

or `double precision`

instead. Adapt accordingly.

Performance will deteriorate for big source tables, as the cost for each next row keeps growing. Something like O(N²).

Carefully table-qualify column names in all queries as the same names are used for multiple purposes.

Alternatively, a **recursive function** could work. Example:

Source: link

"result_good" is the accumulation of "trx" and previous rows from itself, multiplied by "event".

Each result contributes to the next row recursively. This function writes to a temp table and reuses results: Call:Source: link