Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get MAX from a GROUP BY

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?

like image 451
enchance Avatar asked Jan 19 '13 11:01

enchance


People also ask

How do you SELECT the maximum value from multiple columns in SQL?

If you're working with MySQL, you can combine MAX() with the GREATEST() function to get the biggest value from two or more fields. Here's the syntax for GREATEST: GREATEST(value1,value2,...) Given two or more arguments, it returns the largest (maximum-valued) argument.

How do I find the maximum value of a group in SQL?

Discussion: To find the max value of a column, use the MAX() aggregate function; it takes as its argument the name of the column for which you want to find the maximum value. If you have not specified any other columns in the SELECT clause, the maximum will be calculated for all records in the table.

Can you use Max in GROUP BY?

In SQL Server, the MAX() function is an aggregate function that returns the maximum value in the column or expression. It is an aggregate function so it canbe used with the GROUP BY clause to find the maximum value in a group.

Can we use max with GROUP BY in SQL?

The GROUP BY statement is often used with aggregate functions ( COUNT() , MAX() , MIN() , SUM() , AVG() ) to group the result-set by one or more columns.


2 Answers

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
)
like image 99
John Woo Avatar answered Oct 01 '22 19:10

John Woo


Try this query

  SELECT commodity,COUNT(commodity) AS count 
    FROM orders
GROUP BY commodity
ORDER BY count desc
   LIMIT 1;
like image 30
sandip Avatar answered Oct 01 '22 19:10

sandip