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 |
Views: | Raw Message | Whole Thread | Download mbox | Resend email |
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
From | Date | Subject | |
---|---|---|---|
Next Message | Stef | 2004-01-23 12:18:53 | Fw: postgres logging |
Previous Message | Rita Rossinelli-Biagioni | 2004-01-22 16:31:44 | Re: [SQL] Database diagram |