max(), group by and order by

て烟熏妆下的殇ゞ 提交于 2019-12-06 01:59:38

问题


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


回答1:


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



回答2:


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.




回答3:


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.



来源:https://stackoverflow.com/questions/6298703/max-group-by-and-order-by

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!