I have read that grouping happens before ordering, is there any way that I can order first before grouping without having to wrap my whole query around another query just to do this?
Let’s say I have this data:
id | user_id | date_recorded
1 | 1 | 2011-11-07
2 | 1 | 2011-11-05
3 | 1 | 2011-11-06
4 | 2 | 2011-11-03
5 | 2 | 2011-11-06
Normally, I’d have to do this query in order to get what I want:
SELECT
*
FROM (
SELECT * FROM table ORDER BY date_recorded DESC
) t1
GROUP BY t1.user_id
But I’m wondering if there’s a better solution.
Your question is somewhat unclear but I have a suspicion what you really want is not any
GROUPaggregates at all, but rather ordering by date first, then user ID:Here would be the result. Note reordering by
date_recordedfrom your original exampleUpdate
To retrieve the full latest record per user_id, a
JOINis needed. The subquery (mx) locates the latest date_recorded per user_id, and that result is joined to the full table to retrieve the remaining columns.