Find Employees Who Have Worked in More Than One Department Query Using MS SQL Server?
To find employees who have worked in more than one department using Microsoft SQL Server, you'll need to:
- Identify employees with multiple department assignments.
- Aggregate and filter these results to find employees who have been associated with more than one department.
Assuming you have the following tables:
EmployeeDepartmentstable with columns:EmployeeID,DepartmentID,StartDate,EndDate(if applicable).
Here's how you can write a query to find employees who have worked in more than one department:
SQL Query
-- Find employees who have worked in more than one department
WITH DepartmentAssignments AS (
SELECT
EmployeeID,
COUNT(DISTINCT DepartmentID) AS DepartmentCount
FROM
EmployeeDepartments
GROUP BY
EmployeeID
)
SELECT
ea.EmployeeID,
e.EmployeeName -- Assuming you have an Employees table with EmployeeName
FROM
DepartmentAssignments ea
JOIN Employees e ON ea.EmployeeID = e.EmployeeID
WHERE
ea.DepartmentCount > 1
ORDER BY
e.EmployeeID;
Explanation
DepartmentAssignmentsCTE:COUNT(DISTINCT DepartmentID) AS DepartmentCount: Counts the number of distinct departments each employee has worked in.GROUP BY EmployeeID: Groups the results byEmployeeIDto aggregate the number of departments for each employee.
Main Query:
JOIN Employees e ON ea.EmployeeID = e.EmployeeID: Joins with theEmployeestable to get employee details (likeEmployeeName).WHERE ea.DepartmentCount > 1: Filters to get only those employees who have worked in more than one department.ORDER BY e.EmployeeID: Orders the results byEmployeeIDfor better readability.
Additional Considerations
- Data Accuracy: Ensure that the
EmployeeDepartmentstable accurately reflects the departments each employee has worked in. - Handling Dates: If the
EndDateis used, consider scenarios where employees might have overlapping dates or multiple assignments within the same department. - Indexes: Indexes on
EmployeeIDandDepartmentIDcan help improve query performance.
Adjust column names and table structures based on your actual schema. This query will effectively identify employees who have worked in more than one department.

Post a Comment