开发者

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 SE开发者_运维问答LECT 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


SELECT t.client_id, max(t.points) AS "max" 
FROM sessions t
GROUP BY t.client_id 
order by max(t.points) desc


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.


Since you have tagged as Postgres: Postgres allows a non-standard GROUP BY and ORDER BY column number. So you could have

SELECT t.client_id, max(t.points) AS "max" 
FROM sessions t
GROUP BY 1 
order by 2 desc

After parsing, this is identical to RedFilter’s solution.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜