Skip to content

Instantly share code, notes, and snippets.

@joshlk
Created July 4, 2018 14:24
Show Gist options
  • Save joshlk/e1e5a340d077922e9f25e5a1194b28bc to your computer and use it in GitHub Desktop.
Save joshlk/e1e5a340d077922e9f25e5a1194b28bc to your computer and use it in GitHub Desktop.
Postgres custom aggregate functions
-- See: https://stackoverflow.com/questions/48770517/take-first-second-third-last-value-and-selecting-rows-window-function-wit
----- N = 1
-- State transition function
-- agg_state: the current state, el: new element
create or replace function lag_agg_sfunc_1(agg_state point, el float)
returns point
immutable
language plpgsql
as $$
declare
i integer;
stored_value float;
begin
i := agg_state[0];
stored_value := agg_state[1];
i := i + 1; -- First row i=1
if i = 1 then
stored_value := el;
end if;
return point(i, stored_value);
end;
$$;
-- Final function
--DROP FUNCTION lag_agg_ffunc_1(point) CASCADE;
create or replace function lag_agg_ffunc_1(agg_state point)
returns float
immutable
strict
language plpgsql
as $$
begin
return agg_state[1];
end;
$$;
-- Aggregate function
drop aggregate if exists lag_agg_1(double precision);
create aggregate lag_agg_1 (float) (
sfunc = lag_agg_sfunc_1,
stype = point,
finalfunc = lag_agg_ffunc_1,
initcond = '(0,0)'
);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment