Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get number of employees who worked in more than one department with SQL query

I'm trying to figure out a query which show the number (amount) of employees who worked in more than 1 departments. Here the table name and fields:

  • Employee(id_employee, employee_name, salary)
  • Department(id_dept, dept_name, budget)
  • Department_Employee(id_employee, id_dept, workhours_percentage)

Suppose the content of Department_Employee table is

id_employee  id_dept  workhours_percentage
-----------  -------  --------------------
0001           03         100
0001           04          50
0001           05          60
0002           05          60
0002           09          90
0003           08          80
0004           07          80
0005           06          60
0006           05          70
0007           04          75
0008           10          95
0009           02          25
0010           01          40

With a right query, the result should be 2 (employees), because there are 2 employees who work in more than one department

  • Employee 0001 work in 3 departments
  • Employee 0002 work in 2 departments


I tried with the following query

SELECT COUNT(DISTINCT id_employee)
FROM Department_Employee
GROUP BY id_employee
HAVING COUNT(id_employee)>1

But the result isn't right.

Please help me out.

Thanks.

like image 707
Arian Caen Holt Avatar asked Oct 26 '13 15:10

Arian Caen Holt


People also ask

How do I COUNT employees in each department in SQL?

Select the number of employees in each department (you only need to show the department code and the number of employees). SELECT Department, COUNT(*) FROM Employees GROUP BY Department; 10. Select all the data of employees, including each employee's department's data.

How do you COUNT the number of employees in each department?

SELECT department, COUNT(*) AS "Number of employees" FROM employees WHERE state = 'CA' GROUP BY department; Because you have listed one column in your SELECT statement that is not encapsulated in the COUNT function, you must use a GROUP BY clause. The department field must, therefore, be listed in the GROUP BY section.

Which SQL function is used to COUNT the number of employee in the employee table in a SQL query?

The SQL COUNT() is a function that returns the number of records of the table in the output. This function is used with the SQL SELECT statement.

What does COUNT (*) do in SQL?

COUNT(*) returns the number of rows in a specified table, and it preserves duplicate rows. It counts each row separately. This includes rows that contain null values.


1 Answers

SELECT COUNT(*)
FROM
(
SELECT id_employee, COUNT(*) AS CNT
FROM Department_Employee
GROUP BY id_employee
) AS T
WHERE CNT > 1
like image 134
yswai1986 Avatar answered Oct 23 '22 03:10

yswai1986