[英]Get MAX from a GROUP BY
I was practicing some SQL when this hit me. 当我遇到这个时,我正在练习一些SQL。 I wanted to see how many times a certain commodity came up and from there get the commodity which came up the most .
我想知道某种商品出现了多少次,从那里获得了最多的商品。
This shows how many times each commodity comes up: 这表明每种商品出现的次数:
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 |
+-----------------------------------+
I'm trying to get the row with the highest but it's all wrong: 我试图得到最高的行,但这都是错的:
mysql> SELECT commodity, MAX(COUNT(commodity)) count FROM orders GROUP BY commodity ORDER BY count;
What's the right way of doing this? 这样做的正确方法是什么?
CAUTION: the query will not handle duplicate records having the maximum COUNT
注意:查询不会处理具有最大
COUNT
重复记录
SELECT commodity, COUNT(commodity) `count`
FROM orders
GROUP BY commodity
ORDER BY `count` DESC
LIMIT 1
But this will, 但是这会,
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
)
Try this query 试试这个查询
SELECT commodity,COUNT(commodity) AS count
FROM orders
GROUP BY commodity
ORDER BY count desc
LIMIT 1;
我会写:
select * from (SELECT commodity, COUNT(commodity) count FROM orders GROUP BY commodity ORDER BY count desc) where rownum <2;
It is fine just add desc to order by 只需添加desc即可
SELECT commodity, COUNT(commodity) count FROM orders GROUP BY commodity ORDER BY count DESC;
first row will have max value and add limit to get just this one record 第一行将具有最大值并添加限制以获得这一条记录
SELECT commodity, COUNT(commodity) count FROM orders GROUP BY commodity ORDER BY count DESC LIMIT 1;
It looks like you're doing it right. 看起来你做得对。 Except
ORDER BY
orders them in ASC
order. 除了
ORDER BY
以ASC
顺序命令它们。 make it descending 让它下降
mysql> SELECT commodity, COUNT(commodity) count FROM orders GROUP BY commodity ORDER BY count DESC;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.