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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With