Get MAX from a GROUP BY

别说谁变了你拦得住时间么 提交于 2019-12-12 07:35:28

问题


I was practicing some SQL when this hit me. 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?


回答1:


CAUTION: the query will not handle duplicate records having the maximum 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
)



回答2:


Try this query

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



回答3:


I would write:

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



回答4:


It is fine just add desc to order by

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;



回答5:


It looks like you're doing it right. Except ORDER BY orders them in ASC order. make it descending

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


来源:https://stackoverflow.com/questions/14414055/get-max-from-a-group-by

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!