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

Поиск
Список
Период
Сортировка
Искать
От
Christoph Haller
Тема
Re: How can I get the last element out of GROUP BY sets?
Дата
Msg-id
200401191012.LAA26264@rodos
Ответ на
Список
Дерево обсуждения
How can I get the last element out of GROUP BY sets? Robert Creager <Robert_Creager@LogicalChaos.org>
Re: How can I get the last element out of GROUP BY sets? Christoph Haller <ch@rodos.fzk.de>
Re: How can I get the last element out of GROUP BY sets? Tom Lane <tgl@sss.pgh.pa.us>
Re: How can I get the last element out of GROUP BY sets? Robert Creager <Robert_Creager@LogicalChaos.org>
Re: How can I get the last element out of GROUP BY sets? Greg Stark <gsstark@mit.edu>
> 
> I'm trying to produce summary data from a table (using PGSQL 7.4.1):
> 
> CREATE TABLE readings( "when" timestamp, value integer );
> 
> The summary will be based on various time periods.  I've been using date_trunc(
> 'hour', "when" ) and GROUP BY for the min/max/average readings with no problems.
> But, one piece of data I need is the last value for each GROUP BY period.  Alas,
> I cannot figure out how to do this.
> 
> If I wanted to loop from a script, I could, for instance, execute the following
> for each GROUP BY period (filling in ? appropriately):
> 
> SELECT date_trunc( 'hour', "when" ), value
> FROM readings
> WHERE date_trunc( 'hour', "when" )::timestamp =  ?
> ORDER BY "when" DESC
> LIMIT 1
> 
> But, I figure there's probably some what to do this in SQL.
> 
> Any help?
> 
> Thanks,
> Rob
> 
Looks like "SELECT DISTINCT ON" is your friend. RTFM. 

HTH

Regards, Christoph 


В списке pgsql-sql по дате отправления
От: Tom Lane
Дата:
Сообщение: Re: DROP TRIGGER
От: Stephan Szabo
Дата:
Сообщение: Re: Initially Deffered - FK
FAQ