create extension if not exists first_last_agg;
-- Create a function that always returns the first non-NULL item
create function public.first_agg (anyelement, anyelement)
returns anyelement language sql immutable strict as $$
select $1;
$$;
-- and then wrap an aggregate around it
create aggregate public.first (
sfunc = public.first_agg,
basetype = anyelement,
stype = anyelement
);
-- create a function that always returns the last non-null item
create function public.last_agg (anyelement, anyelement)
returns anyelement language sql immutable strict as $$
select $2;
$$;
-- and then wrap an aggregate around it
create aggregate public.last (
sfunc = public.last_agg,
basetype = anyelement,
stype = anyelement
);