Get MAX from a GROUP BY

后端 未结 5 1429
礼貌的吻别
礼貌的吻别 2021-02-09 04:38

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.

相关标签:
5条回答
  • 2021-02-09 05:19

    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;
    
    0 讨论(0)
  • 2021-02-09 05:22

    I would write:

    select * from (SELECT commodity, COUNT(commodity) count FROM orders GROUP BY commodity ORDER BY count desc) where rownum <2;
    
    0 讨论(0)
  • 2021-02-09 05:30

    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
    )
    
    0 讨论(0)
  • 2021-02-09 05:30

    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;
    
    0 讨论(0)
  • 2021-02-09 05:32

    Try this query

      SELECT commodity,COUNT(commodity) AS count 
        FROM orders
    GROUP BY commodity
    ORDER BY count desc
       LIMIT 1;
    
    0 讨论(0)
提交回复
热议问题