开发者

How do I find the oldest record in a group using Postgresql?

开发者 https://www.devze.com 2023-03-13 02:03 出处:网络
Cons开发者_如何学运维ider the following data set in a \"book\" table (group_id, title, check_out_date):

Cons开发者_如何学运维ider the following data set in a "book" table (group_id, title, check_out_date):

> 1 - "Moby Dick" - 2010-01-01
> 1 - "The Jungle Book" - 2011-05-05
> 1 - "Grapes of Wrath" - 1999-01-12
> 2 - "Huckleberry Finn" - 2000-01-05
> 2 - "Tom Sawyer" - 2011-06-12

I need to write a query that will return the record with the oldest "check_out_date" value from each group (Group 1 and Group 2). This should be fairly easy -- I just don't know how to do it.


I think you need something like this.

 select group_id, title, check_out_date from book b1 
       where
       check_out_date = 
       (select MIN(check_out_date) 
       from book b2 where b2.group_id =  b1.group_id)


Now that postgres supports windowing functions.

SELECT group_id, title, checkout_date) FROM
 (SELECT group_id, 
  title, 
  checkout_date, 
  rank() OVER (PARTITION BY group_id ORDER BY checkout_date) AS rk
 ) AS subq
WHERE rk=1;

You probably want an index on (group_id, checkout_date), perhaps vice versa. I haven't banged on windowing enough to know what the planner tries to do.

0

精彩评论

暂无评论...
验证码 换一张
取 消