Created
July 4, 2018 14:24
-
-
Save joshlk/e1e5a340d077922e9f25e5a1194b28bc to your computer and use it in GitHub Desktop.
Postgres custom aggregate functions
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
-- 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