Given a table (“Table”) as follows (sorry about the CSV style since I don’t know how to make it look like a table with the Stack Overflow editor):
id,member,data,start,end 1,001,abc,12/1/2012,12/31/2999 2,001,def,1/1/2009,11/30/2012 3,002,ghi,1/1/2009,12/31/2999 4,003,jkl,1/1/2012,10/31/2012 5,003,mno,8/1/2011,12/31/2011
If using Ruby Sequel, how should I write my query so I will get the following dataset in return.
id,member,data,start,end 1,001,abc,12/1/2012,12/31/2999 3,002,ghi,1/1/2009,12/31/2999 4,003,jkl,1/1/2012,10/31/2012
I get the most current (largest end date value) record for EACH (distinct) member from the original table.
I can get the answer if I convert the table to an Array, but I am looking for a solution in SQL or Ruby Sequel query, if possible. Thank you.
Extra credit: The title of this post is lame…but I can’t come up with a good one. Please offer a better title if you have one. Thank you.
The Sequel version of this is a bit scary. The best I can figure out is to use a subselect and, because you need to join the table and the subselect on two columns, a “join block” as described in Querying in Sequel. Here’s a modified version of Knut’s program above:
This gives you:
In this case it’s probably easier to replace the last four lines with straight SQL. Something like:
Which gives you the same result.