How to find the oldest entry in a group using Postgresql?

Consider the following dataset in the 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 a record with the oldest value "check_out_date" from each group (group 1 and group 2). This should be pretty easy - I just don't know how to do it.

+3
source share
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)
+7
source

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 need an index on (group_id, checkout_date), perhaps the other way around. I did not hit the window to find out what the planner was trying to do.

+2
source

All Articles