从GROUP BY获取MAX

时间:2013-01-19 11:54:50

标签: mysql sql select group-by

当我遇到这个时,我正在练习一些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;

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

5 个答案:

答案 0 :(得分:9)

注意:查询不会处理具有最大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
)

答案 1 :(得分:3)

尝试此查询

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

答案 2 :(得分:0)

我会写:

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

答案 3 :(得分:0)

只需按顺序添加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;

答案 4 :(得分:0)

看起来你做得对。 ORDER BY除外,ASC订单排除。让它下降

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