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.
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.
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.
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.
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.
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;
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)
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
)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With