I have two tables - `employee` and `department`.
1. `employee` table contains column id,employee name and dept_id
2. `department` table contains column id, department name.
I need exact department name which contains
1. maximum employee and
2. no employee
编辑:
Apologizing for bad grammar, here is the example for above two questions what i need.
1. for eg: if two department contains same number of employees, i need to show both department not single by limit.
2. for eg: if more than one department contains 0 employees, i must show those departments particularly.
答案 0 :(得分:4)
select department_name as `department name`,
count(*) as `number of employees`
from employee
inner join department
on employee.dept_id = department.id
group by department_name
order by count(*) desc
limit 1
我认为应该这样做。我一段时间没有对mysql做过任何事情。
编辑:错过了第二个问题
select department_name as `department name`,
count(*) as `number of employees`
from employee
left join department
on employee.dept_id = department.id
group by department_name
HAVING count(*) = 0
答案 1 :(得分:2)
回答第一个问题:
WITH epcount(dept_id, ep_count) AS
(
SELECT dept_id, COUNT(*) AS ep_count
FROM employee
GROUP BY dept_id
)
SELECT d.name FROM epcount AS ec1 JOIN department AS d ON ec1.dept_id=d.id
WHERE NOT EXISTS
(SELECT * FROM epcount AS ec2 WHERE ec1.ep_count < ec2.ep_count)
回答第二个问题:
SELECT name FROM department AS d
WHERE NOT EXISTS
(SELECT * FROM employee AS e WHERE d.id=e.dept_id)
答案 2 :(得分:1)
这将为您提供按部门排序的排序列表,按员工人数排序。
SELECT `dept`.`id`, `dept`.`name`, COUNT(`employee`.`id`) as `employee_count`
FROM `dept` LEFT JOIN `employee`
ON `employee`.`dept_id` = `dept`.`id`
GROUP BY `dept`.`id`
ORDER BY `employee_count`
要获得没有员工的部门,请添加:
AND `employee_count` = 0
......在GROUP BY之前。
要获得员工最多的部门,请将DESC LIMIT 1
添加到最后。
答案 3 :(得分:1)
如果我正确地阅读了这个问题,你需要:
select department_name,
count(employee.dept_id) as num_employees
from department
left join employee on employee.dept_id = department.id
group by department_name
having count(employee.dept_id) = 0 or
count(employee.dept_id) = (select count(dept_id)
from employee
group by employee.id
order by count(dept_id) desc
limit 1)
答案 4 :(得分:0)
显示具有最多员工和员工人数的部门名称的查询:
SELECT department.name, COUNT(employee.name) from department
INNER JOIN employee
ON employee.dept_id = department.id
GROUP BY department.name
ORDER BY COUNT(employee.name) DESC limit 1
显示没有员工的部门的查询:
SELECT department.name from department
LEFT JOIN employee
ON employee.dept_id = department.id
HAVING COUNT(employee.name) = 0
GROUP BY department.name
如果您需要在一个查询中显示它,请粘贴第一个查询,添加UNION ALL,然后粘贴第二个查询。