X-Original-To: pgsql-sql-postgresql.org@localhost.postgresql.org Received: from localhost (av.hub.org [200.46.204.144]) by svr1.postgresql.org (Postfix) with ESMTP id 1F973D82C0 for ; Fri, 18 Nov 2005 23:06:50 -0400 (AST) Received: from svr1.postgresql.org ([200.46.204.71]) by localhost (av.hub.org [200.46.204.144]) (amavisd-new, port 10024) with ESMTP id 31293-07 for ; Sat, 19 Nov 2005 03:06:53 +0000 (GMT) X-Greylist: from auto-whitelisted by SQLgrey- Received: from smtp-send.myrealbox.com (smtp-send.myrealbox.com [151.155.5.143]) by svr1.postgresql.org (Postfix) with ESMTP id 78B0FD6D50 for ; Fri, 18 Nov 2005 23:06:46 -0400 (AST) Received: from [172.16.1.187] grzm [61.197.227.146] by smtp-send.myrealbox.com with NetMail SMTP Agent $Revision: 1.6 $ on Linux via secured & encrypted transport (TLS); Fri, 18 Nov 2005 20:06:51 -0700 In-Reply-To: <20051119025058.LHSU22512.web3-rme.xtra.co.nz@creeping> References: <20051119025058.LHSU22512.web3-rme.xtra.co.nz@creeping> Mime-Version: 1.0 (Apple Message framework v746.2) Content-Type: text/plain; charset=US-ASCII; delsp=yes; format=flowed Message-Id: Cc: Content-Transfer-Encoding: 7bit From: Michael Glaesemann Subject: Re: DISTINCT ON Date: Sat, 19 Nov 2005 12:06:47 +0900 To: "Jeremy Palmer" X-Mailer: Apple Mail (2.746.2) X-Virus-Scanned: by amavisd-new at hub.org X-Spam-Status: No, score=0.945 required=5 tests=[AWL=-0.387, RCVD_IN_BL_SPAMCOP_NET=1.332] X-Spam-Score: 0.945 X-Spam-Level: X-Archive-Number: 200511/156 X-Sequence-Number: 23407 > -----Original Message----- > From: Michael Glaesemann [mailto:grzm@myrealbox.com] > Sent: Saturday, 19 November 2005 12:28 p.m. > On Nov 19, 2005, at 7:49 , Jeremy Palmer wrote: > >> SELECT DISTINCT ON (vector_id, obs_type) >> id >> FROM observation >> ORDER BY vector_id, >> obs_type, >> date DESC; >> >> However the documentation also states that "DISTINCT ON" is not >> part of the >> SQL standard and should be avoided when possible, stating that >> aggregations >> and sub-queries should be used instead... > Something like: > > select max(date), id > from observation > group by vector_id, obs_type; On Nov 19, 2005, at 11:50 , Jeremy Palmer wrote: > Unfortunately that does not work as "id" column needs to be > included in the > group by statement or be used in an aggregate function. If I did > this it > definitely would note return the correct answer, as the "id" column > is the > primary key for the table. [Please don't top post. It makes the post harder to read. I've reordered the post for readability.] Try something like this: select id from ( select max(date) as date vector_id, obs_type from observation group by vector_id, obs_type ) latest_observations join observation using (date, vector_id, obs_type) Michael Glaesemann grzm myrealbox com