X-Original-To: pgsql-sql-postgresql.org@localhost.postgresql.org Received: from localhost (neptune.hub.org [200.46.204.2]) by svr1.postgresql.org (Postfix) with ESMTP id E78F8D1E826 for ; Mon, 19 Jan 2004 10:14:34 +0000 (GMT) Received: from svr1.postgresql.org ([200.46.204.71]) by localhost (neptune.hub.org [200.46.204.2]) (amavisd-new, port 10024) with ESMTP id 65851-04 for ; Mon, 19 Jan 2004 06:14:06 -0400 (AST) Received: from fzkmail2.fzk.de (fzkmail2.fzk.de [141.52.27.52]) by svr1.postgresql.org (Postfix) with SMTP id 4481CD1E805 for ; Mon, 19 Jan 2004 06:13:39 -0400 (AST) Received: FROM resy5.fzk.de BY fzkmail2.fzk.de ; Mon Jan 19 11:13:00 2004 +0100 Received: œby rodos.fzk.de with ESMTP (8.8.6 (PHNE_17135)/8.7.1) id LAA27357; Mon, 19 Jan 2004 11:13:00 +0100 (MET) From: Christoph Haller Message-Id: <200401191012.LAA26264@rodos> Subject: Re: How can I get the last element out of GROUP BY sets? To: Robert_Creager@LogicalChaos.org (Robert Creager) Date: Mon, 19 Jan 2004 11:12:59 MET Cc: pgsql-sql@postgresql.org In-Reply-To: <20040118212834.7c667b9b.Robert_Creager@LogicalChaos.org>; from "Robert Creager" at Jan 19, 104 5:32 am X-Mailer: Elm [revision: 212.4] X-Virus-Scanned: by amavisd-new at postgresql.org X-Amavis-Alert: BAD HEADER Non-encoded 8-bit data (char 9C hex) in message header 'Received' Received: \234by rodos.fzk.de... ^ X-Archive-Number: 200401/165 X-Sequence-Number: 16558 > > 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