Received: from localhost (maia-2.hub.org [200.46.204.187]) by postgresql.org (Postfix) with ESMTP id 4DA659F9B54 for ; Mon, 13 Aug 2007 17:06:17 -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 39195-10 for ; Mon, 13 Aug 2007 17:06:11 -0300 (ADT) X-Greylist: from auto-whitelisted by SQLgrey-1.7.5 Received: from outB.internet-mail-service.net (outB.internet-mail-service.net [216.240.47.225]) by postgresql.org (Postfix) with ESMTP id 046139F9D2F for ; Mon, 13 Aug 2007 17:05:43 -0300 (ADT) Received: from mx0.idiom.com (HELO idiom.com) (216.240.32.160) by out.internet-mail-service.net (qpsmtpd/0.40) with ESMTP; Mon, 13 Aug 2007 13:05:42 -0700 Received: from [192.168.1.109] (adsl-71-135-174-255.dsl.pltn13.pacbell.net [71.135.174.255]) by idiom.com (Postfix) with ESMTP id CB69F125EFA for ; Mon, 13 Aug 2007 13:05:41 -0700 (PDT) Message-ID: <46C0B994.6090906@obviously.com> Date: Mon, 13 Aug 2007 13:05:40 -0700 From: Bryce Nesbitt User-Agent: Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.8.1.4) Gecko/20061107 SUSE/1.1.2-1.1 SeaMonkey/1.1.2 MIME-Version: 1.0 To: pgsql-sql@postgresql.org Subject: Getting pk of the most recent row, in a group by Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 7bit X-Virus-Scanned: Maia Mailguard 1.0.1 X-Archive-Number: 200708/114 X-Sequence-Number: 29052 I've got a table of "coupons" which have an expiration date. For each type of coupon, I'd like to get the primary key of the coupon which will expire first. # create table coupon ( coupon_id serial primary key, type varchar(255), expires date ); insert into coupon values(DEFAULT,'free','2007-01-01'); insert into coupon values(DEFAULT,'free','2007-01-01'); insert into coupon values(DEFAULT,'free','2007-06-01'); insert into coupon values(DEFAULT,'free','2007-06-01'); insert into coupon values(DEFAULT,'50%','2008-06-01'); insert into coupon values(DEFAULT,'50%','2008-06-02'); insert into coupon values(DEFAULT,'50%','2008-06-03'); The desired query would look like: # select coupon_id,type,expires from coupon where type='free' order by expires limit 1; coupon_id | type | expires -----------+------+------------ 1 | free | 2007-01-01 But be grouped by type: # 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? -- ---- Visit http://www.obviously.com/