Click here to Skip to main content
15,881,281 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
want to display that which department have least number of employee ? and department with 2nd least number?

there are three tables
1)departments
*dept_no
*dept_name
2)dept_emp
*emp_no
*dept_no
3)employees
*emp_no
*emp_name

how to join these tables and find which department have least number of employee ? and department with 2nd least number?

What I have tried:

i had tried the following code

SQL
SELECT d.`dept_no`,
       d.`dept_name`,
  count  (dt.emp_no) as "Num of employees"
FROM departments d
  join dept_emp dt
  on d.dept_no=dt.dept_no
  having count(dt.emp_no)=
    (select min(count(de.emp_no))
    from departments d
    join dept_emp dt
    on d.dept_no=dt.dept_no
    group by d.dept_name)
group by d.dept_name;


but its showing error something like
"You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near 'group by d.dept_name' at line 13"
Posted
Updated 31-Dec-19 0:37am
v2

1 solution

Well ... "de" doesn't exist:
SQL
(select min(count(de.emp_no))

And GROUP BY needs to precede HAVING:
SQL
having count(dt.emp_no)=
...
group by d.dept_name;

But why so complicated? A simple JOIN will do it:
SQL
SELECT TOP 2 d.DeptNo, d.DeptName, de.EmpPerDept
FROM Departments d
JOIN (
SELECT DeptNo, COUNT(EmpNo) AS EmpPerDept
FROM DeptEmp 
GROUP BY DeptNo) de
ON de.DeptNo = d.DeptNo
ORDER BY EmpPerDept ASC
 
Share this answer
 
v2
Comments
Oviya Sivakumar 2-Jan-20 0:44am    
it works thank you
OriginalGriff 2-Jan-20 1:59am    
You're welcome!

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900