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

Поиск
Список
Период
Сортировка
От Greg Stark
Тема Re: How can I get the last element out of GROUP BY sets?
Дата
Msg-id 87y8rzxv13.fsf@stark.xeocode.com
обсуждение исходный текст
Ответ на Re: How can I get the last element out of GROUP BY sets?  (Tom Lane <tgl@sss.pgh.pa.us>)
Список 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 по дате отправления:

Предыдущее
От: beyaRecords - The home Urban music
Дата:
Сообщение: Batch update issue
Следующее
От: Stef
Дата:
Сообщение: Fw: postgres logging