Last (aggregate)

From PostgreSQL wiki

Jump to: navigation, search

Library Snippets

Last (aggregate)

Works with PostgreSQL

Any version

Written in

SQL

Depends on

Nothing


This aggregate function returns the value from the last input row in each group.

See also: First (aggregate)

Portable SQL version

This is a portable SQL-language implementation with no external dependencies.

-- Create a function that always returns the last non-NULL item
CREATE OR REPLACE FUNCTION public.last_agg ( anyelement, anyelement )
RETURNS anyelement AS $$
        SELECT $2;
$$ LANGUAGE SQL IMMUTABLE STRICT;
 
-- And then wrap an aggreagate around it
CREATE AGGREGATE public.last (
        sfunc    = public.last_agg,
        basetype = anyelement,
        stype    = anyelement
);

Credit: http://archives.postgresql.org/pgsql-hackers/2006-03/msg01324.php with a couple of corrections.

Fast C version

A faster version written in C is avaiblable in PGXN, called first_last_agg: http://pgxn.org/dist/first_last_agg/

Personal tools