This is my first time trying to build a function in Postgres, and first time working with arrays. And first question on Stackoverflow!
There's a 2 level numeric array of {{a1,b1},{a2,b2}...{ai,bi}}.
Trying to calculate 3 things:
Would like to loop through and multiply each subarray ie
(a1 * b1)and then accumulate within the array, until a certain figure (x) is reached ie(a1 * b1) + (a2 * b2)... + ...(ai * bi) >= x. Soai * biis the first subarray that pushes the accumulation abovex. I want to return this accumulated figure.Cumulative b. ie
(b1 + b2 +...+ bi).ai.
Outside of the loop, I want to do some calculation involving these 3 figures.
Haven't been able to include a DO to localise the variables, but that would be great, if possible.
Looking at around 1M rows. Each row could contain hundreds of subarray elements in the main array but I would be unlikely to need more than 8 subarrays multiplied and summed per row.
Postgres 9.6.
I've looked at foreach and slice in arrays, but not sure if good to use in this case. Not sure if unnest would be any good either. Currently no indexes.
CREATE OR REPLACE FUNCTION accum (numeric[i],numeric[i]) RETURNS numeric AS
$$
DECLARE
x integer := 100;
y numeric;
z numeric;
BEGIN
LOOP
-- Accumulate subarray products
y := SELECT(ANYARRAY)[i:i][1:1]*SELECT(ANYARRAY)[i:i][2:2] + y;
-- Accumulate 2nd element of subarrays
z := SELECT(ANYARRAY)[i:i][2:2] + z;
EXIT WHEN y > x;
END LOOP;
RETURN y,
z,
-- Return first element of subarray that makes y > x
SELECT(ANYARRAY)[i:i][1:1];
"Calculation involving output"
END
$$
LANGUAGE plpgsql
;
I'm unsure as to how to return multiple outputs from a loop. Aiming to get a single numeral output from this function. Any help with the syntax, or the method, of how I'm going about this would be much appreciated! Is it even possible to do all this without a function? Thanks for reading.