0

While looking for an aggregate function that returns the nth element of a collection I found the following solution:

CREATE OR REPLACE FUNCTION _final_nth( anyarray, integer )
  RETURNS anyelement AS
$BODY$
    SELECT a
    FROM unnest( $1 ) a
    ORDER BY a
    offset $2
    LIMIT 1;
$BODY$
LANGUAGE 'sql' IMMUTABLE; 

CREATE AGGREGATE nth( anyelement, integer ) (
  SFUNC=array_append,
  STYPE=anyarray,
  FINALFUNC=_final_nth,
  INITCOND='{}'
); 

Creating the function works fine but executing CREATE AGGREGATE produces the following error:

ERROR: function array_append(anyarray, anyelement, integer) does not exist

I am not able to resolve this error.

1
  • I can't make heads or tails of this question. You say you want the nth element of a collection, but what's a "collection" in PG? If a "collection" is a result set, what's wrong with a straight OFFSET/LIMIT, and if it's an array, what's wrong with a straight myarray[n]? Why do you need an aggregate at all? Also, the error looks pretty obvious to me. PostgreSQL is trying to pass the current state plus the aggregate's arguments to the SFUNC, and there's no array_append that takes those arguments (nor would it make any sense for there to be). Commented Jan 27, 2015 at 7:03

1 Answer 1

1

Maybe this will help:

CREATE OR REPLACE FUNCTION _final_nth( anyarray, integer )
  RETURNS anyelement AS
$BODY$
    SELECT a
    FROM unnest( $1 ) a
    ORDER BY a
    offset $2
    LIMIT 1;
$BODY$

Use it without an extra aggregate-function.

SELECT _final_nth(array_agg(someelement),n) AS someelement
FROM sometable
GROUP BY someelement;

n is the offset.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.