pg.ddx.io  pgsql-sql@postgresql.org mailing list archive  
help / color / mirror / Atom feed
From: Christoph Haller <ch@rodos.fzk.de>
To: Robert_Creager@LogicalChaos.org
Cc: pgsql-sql@postgresql.org
Subject: Re: How can I get the last element out of GROUP BY sets?
Date: Mon, 19 Jan 2004 11:12:59 MET
Message-ID: <200401191012.LAA26264@rodos> (raw)
In-Reply-To: <20040118212834.7c667b9b.Robert_Creager@LogicalChaos.org>

> 
> 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 




view thread (5+ messages)  latest in thread

Message-ID: <200401191012.LAA26264@rodos>
Permalink:  ../200401191012.LAA26264@rodos/
Also on:    postgresql.org/message-id/200401191012.LAA26264@rodos

 · 

reply

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: ch@rodos.fzk.de, Robert_Creager@LogicalChaos.org
  Subject: Re: How can I get the last element out of GROUP BY sets?
  In-Reply-To: <200401191012.LAA26264@rodos>

* 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