从 GROUP BY 中获取 MAX

Posted

技术标签:

【中文标题】从 GROUP BY 中获取 MAX【英文标题】:Get MAX from a GROUP BY 【发布时间】:2013-01-03 01:21:28 【问题描述】:

当我遇到这种情况时,我正在练习一些 SQL。我想看看某种商品出现了多少次,然后从那里得到出现最多的商品。

这显示了每种商品出现了多少次:

mysql> SELECT commodity, COUNT(commodity) count FROM orders GROUP BY commodity ORDER BY count;
+----------------------+------------+
| commodity            |    count   |
+----------------------+------------+
| PERSIAN MELON        |          4 |
| BEANS                |          6 |
| CASABA               |         10 |
| ASPARAGUS            |         11 |
| EGGPLANT             |         12 |
| TOMATOES, CHERRY     |         16 |
| GALIA MELON          |         18 |
+-----------------------------------+

我试图获得最高的那一行,但它完全错了:

mysql> SELECT commodity, MAX(COUNT(commodity)) count FROM orders GROUP BY commodity ORDER BY count;

这样做的正确方法是什么?

【问题讨论】:

【参考方案1】:

注意:查询不会处理具有最大COUNT 的重复记录

SELECT  commodity,  COUNT(commodity) `count` 
FROM    orders 
GROUP   BY commodity
ORDER   BY `count` DESC 
LIMIT   1

但这会,

SELECT  commodity,  COUNT(commodity) `count` 
FROM    orders 
GROUP   BY commodity
HAVING  COUNT(commodity) =
(
    SELECT MAX(`COUNT`) 
    FROM
    (
        SELECT  COUNT(commodity) `count` 
        FROM    orders 
        GROUP   BY commodity
    )   s
)

【讨论】:

@enchance 是的,第一个但第二个不会。考虑这条记录TOMATOES, CHERRY | 18GALIA MELON | 18PERSIAN MELON | 10 第一个将只显示TOMATOES, CHERRY | 18,但第二个将同时显示TOMATOES, CHERRY | 18GALIA MELON | 18 是的,因为它使用LIMIT 1,所以只返回最高记录。有什么方法可以解决这个问题而不必使用子查询?【参考方案2】:

试试这个查询

  SELECT commodity,COUNT(commodity) AS count 
    FROM orders
GROUP BY commodity
ORDER BY count desc
   LIMIT 1;

【讨论】:

MAX(COUNT(commodity)) 无效!【参考方案3】:

我会写:

select * from (SELECT commodity, COUNT(commodity) count FROM orders GROUP BY commodity ORDER BY count desc) where rownum <2;

【讨论】:

【参考方案4】:

只要添加 desc 就可以了

SELECT commodity, COUNT(commodity) count FROM orders GROUP BY commodity ORDER BY count DESC;

第一行将具有最大值并添加限制以获取仅此一条记录

SELECT commodity, COUNT(commodity) count FROM orders GROUP BY commodity ORDER BY count DESC LIMIT 1;

【讨论】:

【参考方案5】:

看起来你做得对。除了ORDER BYASC 的顺序订购它们。让它下降

mysql> SELECT commodity, COUNT(commodity) count FROM orders GROUP BY commodity ORDER BY count DESC;

【讨论】:

MAX(COUNT(commodity)) 无效!

以上是关于从 GROUP BY 中获取 MAX的主要内容,如果未能解决你的问题,请参考以下文章

HSQLDB:原因:使用 MAX,但不使用 Group By,并获取 java.sql.SQLSyntaxErrorException:表达式不在聚合或 GROUP BY 列中:

如何使用group-by并获取其他行结果

sql:group by和 max

PostgreSQL MAX 和 GROUP BY

与 GROUP BY 子句一起使用的 MAX 函数

从 GROUP BY 中获取具有 NULL 列的行