SQL query max(), count()

戏子无情 提交于 2019-12-14 02:15:33

问题


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.


回答1:


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



回答2:


How about something like:

SELECT count( employee_name ) cnt, company_name
FROM works
GROUP BY company_name
ORDER BY cnt DESC
LIMIT 1;

Edit:

Corrected above for MySQL




回答3:


SELECT company_name,count(*) as cnt 
FROM works 
GROUP BY company_name 
ORDER BY cnt DESC



回答4:


select company_name 
from works
group by company_name
having count(distinct employee_name)>=all(select count(distinct employee_name)
from works
group by company_name )



回答5:


Here's the working query

Select * from(SELECT count(EmpName)cnt, CName FROM works GROUP BY CName Order By cnt desc) where ROWNUM = 1;



回答6:


This looks like a course question.

If more than one companies have the same largest number of employees the query with LIMIT doesn't work. "ORDER BY" didn't filter out useless info. Thus we have the following solution

SELECT company_name FROM
(SELECT company_name, count(employee_name) cnt
    FROM works
    GROUP BY company_name) 
JOIN 
(SELECT max(cnt) max_cnt
FROM (
    SELECT count(employee_name) cnt
    FROM works
    GROUP BY company_name
)) ON cnt = max_cnt


来源:https://stackoverflow.com/questions/7832768/sql-query-max-count

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!