How do I get the nth record for each distinct name in a table in rails?

Viewed 232

Essentially I want to get the nth last record for each distinct name.

So if I have a table that looks something like

name    field1
a        1
b        3
a        4
a        2
c        1
c        0
b        3
b        2
c        1

And I wanted to query for the 2nd record of each distinct name (n=2) I would want to get the records

  name    field1
   a       4
   c       0
   b       3

Is there any way to do this in one query. Or do I need to query once for every distinct name?

I have been attempting to use the group function, but could not get it to return anything other than the last record in for each group.

1 Answers
Related