# Find last entry from each category

**URL:** <https://www.ruby-forum.com/t/find-last-entry-from-each-category/188329>\
**Category:** Rails\
**Created:** [May 10, 2010, 11:09am UTC](https://www.ruby-forum.com/t/find-last-entry-from-each-category/188329 "2010-05-10T11:09:09Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![mudge](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/m/258eb7/32.png) [@mudge](https://www.ruby-forum.com/u/mudge)\
**Post date:** [May 10, 2010, 11:09am UTC](https://www.ruby-forum.com/t/find-last-entry-from-each-category/188329/1 "2010-05-10T11:09:09Z")

</div>

Hi,

can anybody help me with to specify a SQL-statement which should do  
following:

Example table (published\_at is a DateTime field)

## id | content | published\_at | author\_id

1 | foo | 2010 | 1  
2 | foo | 2009 | 1  
3 | foo | 2008 | 1  
4 | foo | 2010 | 2  
5 | foo | 2009 | 2  
6 | foo | 2008 | 2  
7 | foo | 2007 | 3

Now, how can I get the last entry (max published\_at) for each author  
The result should be a array with news items 1,4,7

Thanks!

---

<div class="post-metadata">

**Author:** ![mudge](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/m/258eb7/32.png) [@mudge](https://www.ruby-forum.com/u/mudge)\
**Post date:** [May 28, 2010, 12:38pm UTC](https://www.ruby-forum.com/t/find-last-entry-from-each-category/188329/2 "2010-05-28T12:38:54Z")

</div>

No ideas to solve this problem? ☹

---

<div class="post-metadata">

**Author:** ![mudge](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/m/258eb7/32.png) [@mudge](https://www.ruby-forum.com/u/mudge)\
**Post date:** [May 28, 2010, 1:04pm UTC](https://www.ruby-forum.com/t/find-last-entry-from-each-category/188329/3 "2010-05-28T13:04:07Z")

</div>

On 10 May 2010 10:09, Sebastian K. [removed\_email\_address@domain.invalid](mailto:removed_email_address@domain.invalid) wrote:

> how can I get the last entry (max published\_at) for each author  
> The result should be a array with news items 1,4,7

Have you looked at using the “group\_by” method of Enumberable?

[http://apidock.com/rails/Enumerable/group\_by](http://apidock.com/rails/Enumerable/group_by)

You could use it to group by author\_id and then select the latest  
entry from each array.

In raw SQL:  
SELECT id, author\_id, max(published\_at) FROM 'entries group by user\_id

Or in Rails finder:  
Entry.all(:select =\> “\*, max(published\_at)”, :group =\> :author\_id)

Have you read the ActiveRecord API docs? It’s all in there…
