max()、分组依据和排序依据
我有以下 SQL 语句。
SELECT t.client_id,max(t.points) AS "max" FROM sessions GROUP BY t.client_id;
它只是列出了客户 ID 以及他们所获得的最大积分。现在我想按 max(t.points) 对结果进行排序。通常我会使用 ORDER BY,但我不知道如何将它与组一起使用。我知道在以下子句中禁止使用 SELECT 列表中的值,因此在查询末尾添加 ORDER BY max 不起作用。
那么分组后如何对这些结果进行排序呢?
此致
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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
在以下子句中禁止使用
SELECT
列表中的值并不完全正确。事实上,ORDER BY
在SELECT
列表之后进行逻辑处理,并且可以引用SELECT
列表结果名称(与GROUP BY相反) )。因此,编写查询的正常方法是
这种表达方式是 SQL-92,并且应该非常可移植。另一种方法是按列号,例如,
这是在 SQL-92 中执行此操作的唯一两种方法。
SQL:1999 及更高版本还允许引用排序列表中的任意表达式,因此您可以只执行 ORDER BY max(t.points) ,但这显然更麻烦,而且可能不太可移植。按列号排序在 SQL:1999 中被删除,因此它在技术上不再是标准,但可能仍然受到广泛支持。
It is not quite correct that values from the
SELECT
list are prohibited in following clauses. In fact,ORDER BY
is logically processed after theSELECT
list and can refer toSELECT
list result names (in contrast withGROUP BY
). So the normal way to write your query would beThis way of expressing it is SQL-92 and should be very portable. The other way to do it is by column number, e.g.,
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.由于您已标记为 Postgres:Postgres 允许使用非标准
GROUP BY
和ORDER BY
列号。所以你可以在解析之后,这与 RedFilter 的解决方案相同。
Since you have tagged as Postgres: Postgres allows a non-standard
GROUP BY
andORDER BY
column number. So you could haveAfter parsing, this is identical to RedFilter’s solution.