简体   繁体   中英

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.

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
SELECT company_name,count(*) as cnt 
FROM works 
GROUP BY company_name 
ORDER BY cnt DESC

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

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 )

这是工作查询

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

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
select company_name from works_for
group by company_name
having count(employee_name) = (select max(count(employee_name))from works_for
group by company_name);

In Oracle

    select company_name, count(*) as count 
    from works 
    group by company_name
    having count(*) >= all(select count(*) from works group by company_name)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM