Skip site navigation (1) Skip section navigation (2)

Re: How can I get the last element out of GROUP BY sets?

From: Greg Stark <gsstark(at)mit(dot)edu>
To: Tom Lane <tgl(at)sss(dot)pgh(dot)pa(dot)us>
Cc: Robert Creager <Robert_Creager(at)LogicalChaos(dot)org>,PGSQL <pgsql-sql(at)postgresql(dot)org>
Subject: Re: How can I get the last element out of GROUP BY sets?
Date: 2004-01-23 02:23:36
Message-ID: 87y8rzxv13.fsf@stark.xeocode.com (view raw or flat)
Thread:
Lists: pgsql-sql
Tom Lane <tgl(at)sss(dot)pgh(dot)pa(dot)us> writes:

> Robert Creager <Robert_Creager(at)LogicalChaos(dot)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


In response to

pgsql-sql by date

Next:From: StefDate: 2004-01-23 12:18:53
Subject: Fw: postgres logging
Previous:From: Rita Rossinelli-BiagioniDate: 2004-01-22 16:31:44
Subject: Re: [SQL] Database diagram

Privacy Policy | About PostgreSQL
Copyright © 1996-2014 The PostgreSQL Global Development Group