What is the best way to calculate a table where many columns are calculated from other columns in the same table and the formulas build on each other in complex ways.
If you don't care about performance, you could simply calculate each column with its own update statement:
update x set b1 = a1 + a2;
update x set b2 = a3 * b1;
update x set b3 = a4 * b2;
...
Or you can do everything in a single update if you expand the formulas manually:
update x set
b1 = a1 + a2,
b2 = a3 * (a1 + a2),
b3 = a4 * (a3 * (a1 + a2));
The problem here is that these formulas can get huge and hard to change and debug.
Is there some way in Postgres (or maybe even SQL in general) so that you can have both performance and maintainability in these cases?
Here is something I wish I could do:
update x set
b1 = _b1,
b2 = _b2,
b3 = _b3
with
_b1 = a1 + a2,
_b2 = a3 * _b1,
_b3 = a4 * _b2;
I have one working solution where the formulas are defined in a function with multiple return values, but this is rather inflexible in some other ways, so I am looking for alternatives.