Received: from localhost (maia-2.hub.org [200.46.204.187]) by postgresql.org (Postfix) with ESMTP id 41B7E9F949E for ; Mon, 13 Aug 2007 17:19:20 -0300 (ADT) Received: from postgresql.org ([200.46.204.71]) by localhost (mx1.hub.org [200.46.204.187]) (amavisd-maia, port 10024) with ESMTP id 43254-03-2 for ; Mon, 13 Aug 2007 17:19:10 -0300 (ADT) X-Greylist: from auto-whitelisted by SQLgrey-1.7.5 Received: from mtao03.charter.net (mtao03.charter.net [209.225.8.188]) by postgresql.org (Postfix) with ESMTP id 0CA719F9280 for ; Mon, 13 Aug 2007 17:19:12 -0300 (ADT) Received: from aa04.charter.net ([10.20.200.156]) by mtao03.charter.net (InterMail vM.7.08.02.00 201-2186-121-20061213) with ESMTP id <20070813201912.VAHZ10962.mtao03.charter.net@aa04.charter.net>; Mon, 13 Aug 2007 16:19:12 -0400 Received: from [10.0.1.3] (really [66.188.165.91]) by aa04.charter.net with ESMTP id <20070813201912.EXXN1254.aa04.charter.net@[10.0.1.3]>; Mon, 13 Aug 2007 16:19:12 -0400 In-Reply-To: <46C0B994.6090906@obviously.com> References: <46C0B994.6090906@obviously.com> Mime-Version: 1.0 (Apple Message framework v752.2) Content-Type: text/plain; charset=US-ASCII; delsp=yes; format=flowed Message-Id: Cc: pgsql-sql@postgresql.org Content-Transfer-Encoding: 7bit From: Michael Glaesemann Subject: Re: Getting pk of the most recent row, in a group by Date: Mon, 13 Aug 2007 15:19:05 -0500 To: Bryce Nesbitt X-Mailer: Apple Mail (2.752.2) X-Chzlrs: 0 X-Virus-Scanned: Maia Mailguard 1.0.1 X-Archive-Number: 200708/117 X-Sequence-Number: 29055 On Aug 13, 2007, at 15:05 , Bryce Nesbitt wrote: > # select type,min(expires),count(*) from coupon group by type; > type | min | count > ------+------------+------- > free | 2007-01-01 | 4 ; pk=1 > 50% | 2008-06-01 | 3 ; pk=5 > > In the second example, is it possible to get the primary key of the > row > with the minimum expires time? I believe DISTINCT ON will do what you want, if you don't mind using non-SQL-spec functionality: SELECT DISTINCT ON (type) type, expires, coupon_id FROM coupon ORDER BY type, expires; I believe you'd need to add the COUNT using a join: SELECT type, expires, coupon_id, type_count FROM ( SELECT DISTINCT ON (type) type, expires, coupon_id FROM coupon ORDER BY type, expires ) earliest_to_expire JOIN ( SELECT type, count(coupon_id) as type_count FROM coupons GROUP BY type ) type_counts USING (type); Michael Glaesemann grzm seespotcode net