I believe that PostgreSQL (at least 8.3) will require that the DISTINCT ON
expressions must match initial ORDER BY
expressions. I.E. you can't use DISTINCT ON (accountid)
when you have ORDER BY score DESC
. To fix this, add it into the ORDER BY
:
SELECT DISTINCT ON (accountid) *
FROM scoretable
ORDER BY accountid, score DESC
LIMIT 10;
Using this method allows you to select all the columns in a table. It will only return 1 row per accountid even if there are duplicate 'max' values for score.
This was useful for me, as I was not finding the maximum score (which is easy to do with the max() function) but for the most recent time a score was entered for an accountid.