Re: First Aggregate Funtion?

From: Robert Haas <robertmhaas(at)gmail(dot)com>
To: sudalai <sudalait2(at)gmail(dot)com>
Cc: "pgsql-hackers(at)postgresql(dot)org" <pgsql-hackers(at)postgresql(dot)org>
Subject: Re: First Aggregate Funtion?
Date: 2015-07-15 15:01:48
Message-ID: CA+TgmoZ9Osy54hRezZ-JbCYZ-PR0is6bp+pJ9zETH1n2PqHjeQ@mail.gmail.com
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-hackers

On Tue, Jul 14, 2015 at 9:23 AM, sudalai <sudalait2(at)gmail(dot)com> wrote:
> The above implementation of "first" aggregate returns the first non-NULL item
> value.
>
> To get *first row item value* for a column use the below implementation.
>
> -- create a function that push at most two element on given array
> -- push the first row value at second index of the array
> CREATE OR REPLACE FUNCTION two_value_holder(anyarray, anyelement)
> returns anyarray as $$
> select case when array_length($1,1) < 2 then array_append($1,$2) else
> $1 end ;
> $$ language sql immutable;
>
> -- create a function that returns second element of an array
> CREATE OR replace FUNCTION second_element (ANYARRAY)
> RETURNS ANYELEMENT AS $$ SELECT $1[2]; $$ LANGUAGE SQL;
>
> -- create first aggregate function that return first_row item value
> CREATE AGGREGATE first(anyelement)(
> SFUNC=two_value_holder,
> STYPE=ANYARRAY,
> INITCOND='{NULL}',
> FINALFUNC=second_element
> );
>
> I hope this work..

I don't think so, because arrays can contain duplicates.

rhaas=# select coalesce(first(x.column1), 'wrong') from (values
(null), ('correct')) x;
coalesce
----------
wrong
(1 row)

--
Robert Haas
EnterpriseDB: http://www.enterprisedb.com
The Enterprise PostgreSQL Company

In response to

Responses

Browse pgsql-hackers by date

  From Date Subject
Next Message Simon Riggs 2015-07-15 15:24:52 Re: Implementation of global temporary tables?
Previous Message Andres Freund 2015-07-15 14:57:44 Re: Implementation of global temporary tables?