7

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

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

4

5 回答 5

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
)
于 2013-01-19T12:07:05.847 回答
3

试试这个查询

  SELECT commodity,COUNT(commodity) AS count 
    FROM orders
GROUP BY commodity
ORDER BY count desc
   LIMIT 1;
于 2013-01-19T12:00:07.297 回答
0

我会写:

select * from (SELECT commodity, COUNT(commodity) count FROM orders GROUP BY commodity ORDER BY count desc) where rownum <2;
于 2013-01-19T11:59:44.457 回答
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;
于 2013-01-19T12:01:13.473 回答
0

看起来你做对了。除了ORDER BY按顺序订购它们ASC。让它下降

mysql> SELECT commodity, COUNT(commodity) count FROM orders GROUP BY commodity ORDER BY count DESC;
于 2013-01-19T12:02:29.637 回答