从Counting SQL中选择SELECT

时间:2014-05-05 20:20:46

标签: mysql sql sql-server

我从db中提取数据时遇到问题。我的代码如下:

SELECT MAX(maximum)as Number FROM 
(
SELECT department_name, COUNT(employees.employee_id) AS maximum
FROM departments, employees
WHERE departments.department_id=employees.department_id
GROUP BY department_name
)t

结果是:

1   46

这是其中一个部门的最高员工人数。 问题是我想要有46名员工的部门名称的附加栏目。我试过像:

select department_name, count(employees.employee_id)
from departments, employees
where departments.department_id=employees.department_id
group by department_name
having count(employees.employee_id) =
( SELECT MAX(maxx)FROM 
(SELECT department_name, COUNT(employees.employee_id) AS maxx
FROM departments, employees
WHERE departments.department_id=employees.department_id
GROUP BY department_name
);

但它不起作用。请帮忙!

3 个答案:

答案 0 :(得分:0)

试试这个

SELECT t.department_name, MAX(t.maximum) as Number FROM ( 
    SELECT 
        department_name, 
        COUNT(employees.employee_id) AS maximum 
    FROM departments, employees 
    WHERE departments.department_id=employees.department_id 
    GROUP BY department_name 
) t

答案 1 :(得分:0)

如何按照限制1的最低顺序排列结果,也使用现代连接语法查询

SELECT d.department_name, 
COUNT(e.employee_id) AS maximum
FROM departments d
LEFT JOIN employees e
ON (d.department_id=e.department_id)
GROUP BY d.department_name
ORDER BY maximum DESC 
LIMIT 1

这将为您提供员工人数最多的部门名称

答案 2 :(得分:0)

您还可以对您发布的第一个查询添加一个额外的JOIN:

SELECT TOP 1 d.department_name, MAX(maximum) as Number FROM ( SELECT department_id AS department_id, COUNT(employees.employee_id) AS maximum FROM departments, employees WHERE departments.department_id=employees.department_id GROUP BY department_id )t JOIN departments d ON d.department_id = t.department_id GROUP BY d.department_name ORDER BY Number DESC

我在我的域中使用类似的数据模型尝试了这个并且它运行得非常好。