From: Greg Stark <gsstark@mit.edu>
To: Tom Lane <tgl@sss.pgh.pa.us>
Cc: Robert Creager <Robert_Creager@LogicalChaos.org>
Cc: PGSQL <pgsql-sql@postgresql.org>
Subject: Re: How can I get the last element out of GROUP BY sets?
Date: 22 Jan 2004 21:23:36 -0500
Message-ID: <87y8rzxv13.fsf@stark.xeocode.com> (raw)
In-Reply-To: <20989.1074491070@sss.pgh.pa.us>
References: <20040118212834.7c667b9b.Robert_Creager@LogicalChaos.org>
<20989.1074491070@sss.pgh.pa.us>
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
Reply instructions:
You may reply publicly to this message via plain-text email
using any one of the following methods:
* Reply to all the recipients using the --to and --cc options:
reply via email
To: pgsql-sql@postgresql.org
Cc: gsstark@mit.edu, tgl@sss.pgh.pa.us, Robert_Creager@LogicalChaos.org
Subject: Re: How can I get the last element out of GROUP BY sets?
In-Reply-To: <87y8rzxv13.fsf@stark.xeocode.com>
* Save the following mbox file, import it into your mail client,
and reply-to-all from there: mbox
This inbox is served by DDX for PostgreSQL; see mirroring instructions
for how to clone and mirror all data and code used for this inbox