0

I have an Employee table and another one EmployeeManager, I need to do a query to show all employees that are not managers and another one that shows all employees that are managers.

This is the first query:

SELECT E.EmployeeId, E.FirstName, E.LastName
  FROM Employee E
 INNER JOIN (SELECT a.EmployeeId,
                (SELECT COUNT(*) FROM EmployeeManager b 
                      WHERE a.EmployeeId = b.Managerid) IsManager
               FROM EmployeeManager a) ER
    ON E.EmployeeId = ER.EmployeeId
   AND ER.IsManager = 0

Is there any better option? because I don't like at all.

2
  • 1
    why don't you like this? Commented Jan 10, 2014 at 17:08
  • Good question @HLGEM.. OP: Can you show some data or a fiddle? Commented Jan 10, 2014 at 17:10

1 Answer 1

1

All Employees that are Managers:

SELECT   E.EmployeeId, E.FirstName, E.LastName
FROM     Employee E
JOIN     EmployeeManager M ON E.EmployeeId = M.ManagerId

All Employees that are not Managers:

SELECT   EmployeeId, FirstName, LastName
FROM     Employee
WHERE    EmployeeId NOT IN 
         (
             SELECT   ManagerId 
             FROM     EmployeeManager 
             WHERE    ManagerId IS NOT NULL
         )

Note: I added the WHERE ManagerId IS NOT NULL due to a comment from @usr that suggested NULLs may be allowed for ManagerId, which would cause the NOT IN to fail. Without knowing the schema, this covers that scenario.

Sign up to request clarification or add additional context in comments.

4 Comments

Clean, minimal and fast. +1. But: The NOT IN will not work due to NULL values. Filter them out.
@usr - I'm not following. Wouldn't it only be pulling Employees who aren't in the EmployeeManager table? Where are the NULL values coming from?
Maybe EmployeeManager.ManagerId can contain nulls. If there is just one NULL, the NOT IN will never match anything.
@usr - I assumed it was an identity column, but just incase you are right, I edited the post since we don't know what they OP's schema is.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.