Mysql
 sql >> Base de données >  >> RDS >> Mysql

Obtenir MAX d'un GROUP BY

ATTENTION :la requête ne traitera pas les enregistrements en double ayant le maximum de COUNT

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

Mais ce sera,

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
)