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.
You can use
orderto get your records ordered by theirnameattribute:Then use
pluckto get only thenameandfield1attribute:With that you can work over your result as a hash and use
group_byto group them by their first element:And then use map to get the second array value for every key value in the main hash:
So you could try with: