Find Employees with More Than One Manager Using MS SQL Server Query?
To find employees who report to more than one manager, you can use a combination of SQL aggregation and grouping functions. Assume you have a table named EmployeeManagers
with the following columns:
EmployeeID
: The ID of the employee.ManagerID
: The ID of the manager.
Here's a step-by-step SQL query to identify employees with more than one manager:
SQL Query
Explanation:
GROUP BY EmployeeID
:- This groups the rows by
EmployeeID
, so that you can aggregate data for each employee.
- This groups the rows by
COUNT(DISTINCT ManagerID)
:- This counts the number of distinct managers for each employee.
HAVING COUNT(DISTINCT ManagerID) > 1
:- The
HAVING
clause filters the results to include only those employees who have more than one distinct manager.
- The
Example
Consider the following example data in the EmployeeManagers
table:
EmployeeID | ManagerID |
---|---|
1 | 100 |
1 | 101 |
2 | 100 |
3 | 102 |
3 | 103 |
3 | 100 |
Using the provided query, the result will be:
EmployeeID |
---|
1 |
3 |
This result indicates that employees with IDs 1 and 3 have more than one manager.
You can run this query in SQL Server Management Studio or any SQL query tool connected to your SQL Server to find employees with more than one manager.
Post a Comment