Re: How can I get the last element out of GROUP BY sets? - Mailing list pgsql-sql

From Greg Stark
Subject Re: How can I get the last element out of GROUP BY sets?
Date
Msg-id 87y8rzxv13.fsf@stark.xeocode.com
Whole thread Raw
In response to Re: How can I get the last element out of GROUP BY sets?  (Tom Lane <tgl@sss.pgh.pa.us>)
List pgsql-sql
Tom Lane <tgl@sss.pgh.pa.us> writes:

> Robert Creager <Robert_Creager@LogicalChaos.org> writes:
> > ... one piece of data I need is the last value for each GROUP BY
> > period.  Alas, I cannot figure out how to do this.
> 
> SELECT DISTINCT ON (rather than GROUP BY) could get this done for you.

Or if you need to combine this with other aggregate functions like sum, count,
etc:

CREATE FUNCTION first_accum (integer, integer) RETURNS integer AS 'select coalesce($1,$2)' LANGUAGE sql;
CREATE FUNCTION last_accum (integer, integer) RETURNS integer AS 'select $2' LANGUAGE sql;
CREATE AGGREGATE first (BASETYPE = integer, SFUNC = first_accum, STYPE = integer);
CREATE AGGREGATE last (BASETYPE = integer, SFUNC = last_accum, STYPE = integer);

Then you can do first() and last(). These definitions only work for integer
but you can pattern match for other datatypes. You might be able to get a
universal function working using anyelement now, I haven't tried.

-- 
greg



pgsql-sql by date:

Previous
From: beyaRecords - The home Urban music
Date:
Subject: Batch update issue
Next
From: Stef
Date:
Subject: Fw: postgres logging