Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL query max(), count()

the database schema looks like

employee(employee_name,street,city)
works(employee_name,company_name,salary)
company(company_name,city)
manages(employee_name,manager_name)

the query needed to do is:
find the company that has the most employees.

I could find out the maximum count by the query:

SELECT max( cnt ) max_cnt
FROM (

SELECT count( employee_name ) cnt, company_name
FROM works
GROUP BY company_name
)w1;

But now I can't find out the name of the company. If anyone has some idea please share.

like image 942
Dolphin Avatar asked Mar 25 '26 10:03

Dolphin


1 Answers

To get the entire row containing the maximum value you can use ORDER BY ... DESC LIMIT 1 instead of MAX:

SELECT company_name, cnt
FROM (
    SELECT company_name, count(employee_name) AS cnt
    FROM works
    GROUP BY company_name
) w1
ORDER BY cnt DESC
LIMIT 1
like image 171
Mark Byers Avatar answered Mar 26 '26 23:03

Mark Byers



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!