Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL - Displaying entries that are the max of a count?

Tags:

CREATE TABLE doctor( patient CHAR(13), docname CHAR(30) );

Say I had a table like this, then how would I display the names of the doctors that have the most patients? Like if the most was three and two doctors had three patients then I would display both of their names.

This would get the max patients:

SELECT MAX(count) 
FROM (SELECT COUNT(docname) FROM doctor GROUP BY docname) a;

This is all the doctors and how many patients they have:

SELECT docname, COUNT(docname) FROM doctor GROUP BY name;

Now I can't figure out how to combine them to list only the names of doctors who have the max patients.

Thanks.

like image 494
Stewage Avatar asked Mar 01 '11 20:03

Stewage


People also ask

Can I use max count ()) in SQL?

No, we can't use a MAX(COUNT(*) and we can not layer aggregate functions on top of one another in the same SELECT clause. In a subquery, the inner aggregate would have to be performed.

How do you find Max count in SQL?

The solution is to use the first table as a subquery. We will create an additional query, an outer query, which uses the first table in its FROM clause. It will be able to use MAX() on the COUNT() result from the first table, thus circumventing the direct use of two layered aggregate functions.

How do you show max and min in SQL?

To ask SQL Server about the minimum and maximum values in a column, we use the following syntax: SELECT MIN(column_name) FROM table_name; SELECT MAX(column_name) FROM table_name; When we use this syntax, SQL Server returns a single value.

Can we use MAX function in where clause?

Overview. The MAX() function is used with the WHERE clause to gain further insights from our data. In SQL, the MAX() function computes the highest or maximum value of numeric values in a column.


3 Answers

This should do it.

SELECT docname, COUNT(*) FROM doctor GROUP BY name HAVING COUNT(*) =      (SELECT MAX(c) FROM         (SELECT COUNT(patient) AS c          FROM doctor          GROUP BY docname)) 

On the other hand if you require only the first entry, then

SELECT docname, COUNT(docname) FROM doctor  GROUP BY name  ORDER BY COUNT(docname) DESC LIMIT 1; 
like image 169
manish_s Avatar answered Oct 23 '22 19:10

manish_s


This should do it for you:

SELECT docname FROM doctor GROUP BY docname HAVING COUNT(patient)=     (SELECT MAX(patientcount) FROM         (SELECT docname,COUNT(patient) AS patientcount          FROM doctor          GROUP BY docname) t1) 
like image 25
squillman Avatar answered Oct 23 '22 19:10

squillman


Here's another alternative that only has one subquery instead of two:

SELECT docname
FROM author
GROUP BY name
HAVING COUNT(*) = (
    SELECT COUNT(*) AS c
    FROM author
    GROUP BY name
    ORDER BY c DESC
    LIMIT 1
)
like image 25
Mark Byers Avatar answered Oct 23 '22 20:10

Mark Byers