Received: from maia.hub.org (maia-2.hub.org [200.46.204.251]) by mail.postgresql.org (Postfix) with ESMTP id 34ECA1337999 for ; Thu, 31 Mar 2011 20:32:29 -0300 (ADT) Received: from mail.postgresql.org ([200.46.204.86]) by maia.hub.org (mx1.hub.org [200.46.204.251]) (amavisd-maia, port 10024) with ESMTP id 16310-08 for ; Thu, 31 Mar 2011 23:32:12 +0000 (UTC) X-Greylist: delayed 00:17:08.815116 by SQLgrey-1.7.6 Received: from mail1.automotive.com (mail1.automotive.com [12.131.237.150]) by mail.postgresql.org (Postfix) with ESMTP id 76FC31337B2F for ; Thu, 31 Mar 2011 20:32:11 -0300 (ADT) Received: from mail1.automotive.com ([10.0.0.23]) by mail1.automotive.com with Microsoft SMTPSVC(6.0.3790.4675); Thu, 31 Mar 2011 16:16:25 -0700 X-MimeOLE: Produced By Microsoft Exchange V6.5 Content-class: urn:content-classes:message MIME-Version: 1.0 Content-Type: text/plain; charset="us-ascii" Content-Transfer-Encoding: quoted-printable Subject: Re: Aggregates puzzle Date: Thu, 31 Mar 2011 16:14:59 -0700 Message-ID: <216FFB77CBFAEE4B8EE4DF0A939FF1D14F8564@mail-001.corp.automotive.com> In-Reply-To: <4D94E0CB.4020309@noaa.gov> X-MS-Has-Attach: X-MS-TNEF-Correlator: Thread-Topic: [SQL] Aggregates puzzle Thread-Index: Acvv4GU/8z3bqkyJRnmQCfgSROryzQAGKr3Q References: <4D94E0CB.4020309@noaa.gov> From: "Ozer, Pam" To: "Mark Fenbers" , "PostgreSQL - SQL" X-OriginalArrivalTime: 31 Mar 2011 23:16:25.0275 (UTC) FILETIME=[A7E2E0B0:01CBEFF9] X-Virus-Scanned: Maia Mailguard 1.0.1 X-Spam-Status: No, hits=-1.91 tagged_above=-5 required=5 tests=BAYES_00=-1.9, T_RP_MATCHES_RCVD=-0.01 X-Spam-Level: X-Archive-Number: 201103/45 X-Sequence-Number: 35247 Try this. Once you know the value you want you have to join back to find the time of that value. Select f.Lid, F.Value,F.event_id, f.obstime From ( SELECT lid, MAX(value) As Value, event_id FROM flood_ts GROUP BY lid, event_id )sub Join flood f On sub.Value=3Df.value and f.lid=3Dsub.lid and sub.event_id=3Dv.event_id -----Original Message----- From: pgsql-sql-owner@postgresql.org [mailto:pgsql-sql-owner@postgresql.org] On Behalf Of Mark Fenbers Sent: Thursday, March 31, 2011 1:15 PM To: PostgreSQL - SQL Subject: [SQL] Aggregates puzzle SQL gurus, I have a table with 4 columns: lid(varchar), value(float), obstime(datetime), event_id(integer) I want to find the MAX(value) and the time and date that it occurred (obstime) in each group of rows where the lid and event_id are the same. What I have works correctly in identifying the MAX(value) for the given group, but I'm having trouble getting the corresponding obstime to be reported along with it. Here's the SQL I have: SELECT lid, MAX(value), event_id FROM flood_ts GROUP BY lid, event_id ORDER BY lid; If I add "obstime" to the SELECT list, then I need to add "value" to the GROUP BY clause, which makes the MAX(value) function report *each row* as a maximum. So, how can I revise my SQL to report the obstime that the MAX(value) occurred? Any help is sincerely appreciated. Mark