I have a message table that looks like this:
+------------+-------------+----------+ | sender_id | created_at | message | +------------+-------------+----------+ | 1 | 2010-06-14 | the msg | | 1 | 2010-06-15 | the msg | | 2 | 2010-06-16 | the msg | | 3 | 2010-06-14 | the msg | +------------+-------------+----------|
I want to select the only last message for each sender.
This is similar to GROUP BY sender_id and ORDER BY created_at, but I am having trouble displaying the most recent message.
I use postgres, so I need the aggregate function in the created_at file in the SELECT statement if I want to order this field, so I was looking to do something like this as an initial test
SELECT messages.sender_id, MAX(messages.created_at) as the_date FROM messages GROUP BY sender_id ORDER BY the_date DESC LIMIT 10;
This seems to work, but when I want to select the βmessageβ, I donβt know what function of the unit to use on it. I just want the message to match MAX created_at.
Is there a way to get to this or am I approaching it wrong?
source share