23

Please let me know what is wrong with the below command

mysql> select max(count(*)) from emp1 group by name;
ERROR 1111 (HY000): Invalid use of group function
3
  • I suppose that there are several lines in the table where name has the same value. He wants to find the name with the largest number of lines. Commented May 8, 2013 at 12:48
  • 1
    Are you trying to count the name and then only return the highest count?
    – SOfanatic
    Commented May 8, 2013 at 12:48
  • You cannot aggregate an aggregate within the same scope
    – Strawberry
    Commented Feb 19, 2016 at 8:31

9 Answers 9

36

Try:

SELECT NAME, 
       COUNT(*) as c 
FROM table 
GROUP BY name 
ORDER BY c DESC LIMIT 1
1
  • 1
    matsko approved Halley's edit, which added NAME, to the select. However, if the goal is to simply get back the scalar value of the maximum count, this change was not needed. In that case, can simply use the original code: SELECT COUNT(*) as c FROM table GROUP BY name ORDER BY c DESC LIMIT 1. Commented Aug 24, 2020 at 19:54
26

From the supplied code I understand that you wish to select the highest number of employees that share the same name.

The problem with your query is that you are trying to apply more than one level of aggregation in a single scope.

Try this:

SELECT MAX(Total) FROM (SELECT COUNT(*) AS Total FROM emp1 GROUP BY name) AS Results

...or this:

SELECT COUNT(name) FROM emp1 GROUP BY name ORDER BY COUNT(name) DESC LIMIT 1

Both queries return the same result, but their implementations are different.

Use whichever is the fastest for you or whichever you prefer.

2
  • 1
    Unless we're being particularly pedantic, I think this provides an answer - although order by limit would be more usual
    – Strawberry
    Commented Feb 19, 2016 at 8:32
  • The subquery is more canonical, as the order by limit is more a hack, so you see both in the wild. The first is most often written by programmers having formal education in data persistence, but we really can see it.
    – Dereckson
    Commented Mar 11, 2020 at 13:32
6

I'd to the following (assuming I understand correctly what you want):

select c from
(
    select count(*) as c, name from emp1 group by name
) tmp
order by c desc limit 1

This selects the largest count from all counts by name. For example, if your table contains

Name
-----------------------
Test
Test
Hello
World
World
World

The inner select would create a "table" with this data

c         Name
----------------------
2         Test
1         Hello
3         World

The outer select would order this by c descending and select the first entry, which is 3.

This can be shortened to

select count(*) c from emp1 group by name order by c desc limit 1
1
  • 1
    Obviously, the outer query's not required here. ORDER BY COUNT(*) DESC LIMIT 1 would do just as well
    – Strawberry
    Commented May 8, 2013 at 12:52
6

You are asking "what is wrong with your statement". This is your statement:

select max(count(*))
from emp1
group by name;

I understand what you mean. But a SQL Compiler does not. The reason is simple. A given select can have only one group by clause. And your query is asking for two of them. The first is the group by name. The second is an aggregation on all those results.

The proper way to write your query (as you seem to intend) is using a subquery:

select max(cnt)
from (select count(*) as cnt
      from emp1
      group by name
     ) t

This is a perfectly reasonable solution that only uses standard SQL. Other answers have proposed the solution using the limit clause, which may be a bit more efficient.

2

You must select name to group by it, then use max() on the result of that as a subquery:

select max(count)
from (
  select
    name,
    count(*) as count
  from emp1
  group by name) x

I have formatted the query so you can see what's happening, rather than put it all on one line as you showed it. Btw the "x" at he fnf is a required alias for the subquery.

1
SELECT  MAX(name_count)
FROM
        (
        SELECT  name
                ,count(*) as name_count
        FROM    emp1 
        GROUP BY
                name
        )
1
  • 2
    Is there a way to also select the name in the outermost SELECT statement? So if you wanted to know which name group was the one with the MAX(name_count)?
    – Logan
    Commented May 31, 2017 at 21:44
0

In case the data happened to have multi occurrences for the max value the LIMIT 1 will not answer the question. In order to illustrate this, I used the WOLRD database sample from MySQL to answer this question.

Q) Return the list of the country(ies) that has the highest number of languages.

FIVE countries fit to have the same number of languages which is 12 namely

  1. Canada
  2. China
  3. India
  4. Russia
  5. USA

Firstly, we need to create a VIEW to hold the max value (in this case is 12)

CREATE VIEW abc AS SELECT count(countrycode) AS total FROM 
countrylanguage GROUP BY countrycode 
ORDER BY COUNT(countrycode) DESC limit 1;

then use the view in the SELECT statement below:

SELECT `name`, COUNT(country.`name`) FROM country JOIN    
countrylanguage ON country.`code` = countrylanguage.countrycode 
GROUP BY country.`name` 
HAVING COUNT(country.`name`) = (SELECT total FROM abc) ;
0

you didn't need max here i think you want know the employee count

then use just count()
like this

select count(*) from emp1

but here another example for use max with count for example we need to know most author have many books

SELECT  book_author.`author_id`
,  COUNT(book_author.`book_id`)  AS books_count
 FROM book_author
GROUP BY book_author.`author_id`
HAVING   COUNT(book_author.`book_id`)=(SELECT MAX(t1.book_count) 
 FROM 
(SELECT COUNT(book_author.`book_id`)  AS book_count 
FROM  book_author
GROUP BY book_author.`author_id` )t1
)
-1
 ***Example: 1***
 SELECT *
 FROM customer
 WHERE customer.ID IN
      (SELECT customer_id
         FROM (SELECT customer_id, MAX(cust_count)
                 FROM (SELECT customer_id,
                              COUNT(customer_id)
                                 AS cust_count
                         FROM `order`
                       GROUP BY customer_id) AS cust_count_tbl) AS cust_tbl);


***Example -2*** 

SELECT *
      FROM    customer
   LEFT JOIN
      (SELECT customer_id, COUNT(customer_id) AS cc
         FROM `order`
       GROUP BY customer_id
       ORDER BY cc DESC
        LIMIT 1) AS kk
   ON customer.ID = kk.customer_id
   WHERE kk.customer_id = customer.ID;

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.