给定关系架构:
Emp(e_name,street,city)
Works_for(e_name,company_name,salary)
公司(company_name,city)
管理(e_name,manager_name)
查询:找到最多没有员工的公司。
我的尝试:
SELECT company_name, max(count(e_name))
FROM Works_for
GROUP BY company_name
^这会产生错误:不是单个组组功能。 对此有什么正确的查询?
感谢您的帮助!
答案 0 :(得分:6)
由于您需要 table 最大值,因此可以使用ORDER BY ... DESC LIMIT 1
:
SELECT company_name, COUNT(e_name) AS cnt
FROM Works_for
GROUP BY company_name
ORDER BY cnt DESC
LIMIT 1
更新
不使用LIMIT
就不那么令人愉快了:
SELECT MAX(company_name)
FROM
(
SELECT company_name AS company_name
FROM Works_for
GROUP BY company_name
HAVING COUNT(*) = (
SELECT MAX(cnt) FROM
(
SELECT COUNT(e_name) AS cnt
FROM Works_for
GROUP BY company_name
) T1
)
) T2
答案 1 :(得分:3)
尝试:
SELECT company_name, count(e_name) count
FROM Works_for
GROUP BY company_name
ORDER BY count desc
然后抓住最顶层的
答案 2 :(得分:1)
要尝试避免限制,您可以使用having子句:
SELECT company_name, count(e_name)
FROM Works_for
GROUP BY company_name
HAVING count(e_name) = (
SELECT max( count(e_name) )
FROM Works_for
GROUP BY company_name );
但真正的限制是一个更简单的选择!