Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

max(), group by and order by

I have following SQL statement.

    SELECT t.client_id,max(t.points) AS "max" FROM sessions GROUP BY t.client_id;

It simply lists client id's with maximum amount of points they've achieved. Now I want to sort the results by max(t.points). Normally I would use ORDER BY, but I have no idea how to use it with groups. I know using value from SELECT list is prohibited in following clauses, so adding ORDER BY max at the end of query won't work.

How can I sort those results after grouping, then?

Best regards

like image 544
stilz Avatar asked Jun 09 '11 20:06

stilz


2 Answers

SELECT t.client_id, max(t.points) AS "max" 
FROM sessions t
GROUP BY t.client_id 
order by max(t.points) desc
like image 155
D'Arcy Rittich Avatar answered Sep 28 '22 22:09

D'Arcy Rittich


It is not quite correct that values from the SELECT list are prohibited in following clauses. In fact, ORDER BY is logically processed after the SELECT list and can refer to SELECT list result names (in contrast with GROUP BY). So the normal way to write your query would be

SELECT t.client_id, max(t.points) AS "max"
    FROM sessions
    GROUP BY t.client_id
    ORDER BY max;

This way of expressing it is SQL-92 and should be very portable. The other way to do it is by column number, e.g.,

    ORDER BY 2;

These are the only two ways to do this in SQL-92.

SQL:1999 and later also allow referring to arbitrary expressions in the sort list, so you could just do ORDER BY max(t.points), but that's clearly more cumbersome, and possibly less portable. The ordering by column number was removed in SQL:1999, so it's technically no longer standard, but probably still widely supported.

like image 25
Peter Eisentraut Avatar answered Sep 28 '22 23:09

Peter Eisentraut