I'm looking for a first() aggregate function.
Here I found something that almost works:
CREATE OR REPLACE 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
);
The problem is that when a varchar(n) column passes through the first() function, it's converted into simple varchar (without size modifier). Trying to return the query in a function as RETURNS SETOF anyelement, I get the following error:
ERROR: structure of query does not match function result type Estado de
SQL:42804
Detalhe:Returned type character varying does not match expected type character varying(40) in column 2.
Contexto:PL/pgSQL function vsr_table_at_time(anyelement,timestamp without time zone) line 31 at RETURN QUERY
In the same wiki page there is a link to a C Version of the function that would replace the above. I don't know how to install it, but I wonder if this version could solve my problem.
Meanwhile, is there a way I can change the above function so it returns the exact same type of the input column?
DISTINCT ONwill not work in this case. It's not an aggregate function, you are actually filtering the data and so you can only do it once. – DB140141 Dec 17 '18 at 19:27CASEstatement in theDISTINCT ONexpression - e.g.SELECT DISTINCT ON (CASE IF group_id IS NOT NULL THEN group_id ELSE other_unique_key END)which works perfectly. – Aaron D May 05 '21 at 15:02percentile_disc(0) WITHIN GROUP (ORDER BY z)worked perfectly for me even for string/jsonb columns where I just wanted the first or any value (just a sample) for that column. min/max work on text columns but not on json/jsonb. For my use case,mode() WITHIN GROUP (ORDER BY z)also worked (to get the most frequent value). – henfiber Jun 14 '22 at 07:26