From: | Terry Fielder <terry(at)ashtonwoodshomes(dot)com> |
---|---|
To: | Bryce Nesbitt <bryce1(at)obviously(dot)com> |
Cc: | pgsql-sql(at)postgresql(dot)org |
Subject: | Re: Getting pk of the most recent row, in a group by |
Date: | 2007-08-13 23:19:10 |
Message-ID: | 46C0E6EE.6080805@ashtonwoodshomes.com |
Views: | Raw Message | Whole Thread | Download mbox | Resend email |
Thread: | |
Lists: | pgsql-sql |
Do you have a table of coupon types?
Terry
Terry Fielder
terry(at)greatgulfhomes(dot)com
Associate Director Software Development and Deployment
Great Gulf Homes / Ashton Woods Homes
Fax: (416) 441-9085
Bryce Nesbitt wrote:
> 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?
>
>
From | Date | Subject | |
---|---|---|---|
Next Message | Christian Kindler | 2007-08-14 06:17:17 | Re: how to move back in refcursor |
Previous Message | Jim Nasby | 2007-08-13 22:17:16 | Re: Performance on writable views |