Mysql
 sql >> Base de Dados >  >> RDS >> Mysql

Obtenha MAX de um GROUP BY


CUIDADO:a consulta não lidará com registros duplicados com o máximo de COUNT
SELECT  commodity,  COUNT(commodity) `count` 
FROM    orders 
GROUP   BY commodity
ORDER   BY `count` DESC 
LIMIT   1

Mas isso vai,
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
)