Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

sql

postgresql

Consider 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.

like image 241
Huuuze Avatar asked Jun 15 '11 19:06

Huuuze


2 Answers

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)
like image 131
NullRef Avatar answered Oct 21 '22 21:10

NullRef


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.

like image 24
Andrew Lazarus Avatar answered Oct 21 '22 19:10

Andrew Lazarus