Easiest way to find IsManager in SQL

2019-08-30 08:26发布

Simple structure table of employees

Employee      Manager
Joe Smith      Jon Smith
Jon Smith      Pete Stevens
Pete Stevens   NULL
Jared Scho     Pete Stevens
....

Im just trying to return some results but I want an indicator on whether the person is a manager or not so the result should be:

Employee       Manager      IsAManager
Joe Smith     Jon Smith         0
Jon Smith     Pete Stevens      1
Pete Stevens    NULL            1
Jared Scho    Pete Stevens      0

The result set is showing that Joe Smith and Jared Scho are not managers...

So If I had a simple SQL Query

SELECT
   Employee,
   Manager,
   As IsAManager   --tried to do a case statement here....
FROM
   Employee

I tried to do a case statement something to this effect:

SELECT CASE ISNULL(COUNT(*), 0) > 0 THEN 1 ELSE 0 END FROM Employee WHERE Manager = Employee

Not sure how to word it :)

2条回答
贪生不怕死
2楼-- · 2019-08-30 08:59

Hopefully this is just a demo example not your real table structure.

SELECT Employee,
       Manager,
       CASE
         WHEN EXISTS(SELECT *
                     FROM   Employee e2
                     WHERE  e2.Manager = e1.Employee) THEN 1
         ELSE 0
       END As IsAManager
FROM   Employee e1  

For details of how SQL Server processes EXISTS Subqueries in CASE Expressions see this article.

查看更多
祖国的老花朵
3楼-- · 2019-08-30 09:18

To determine whether an employee is a manager, you need to match the Employee's ID (in this case, the name) against the list of Manager IDs (in this case the Manager column). If you find a match, the employee is a manager. If you don't find a match, the employee is not a manager.

You can do this with a LEFT OUTER JOIN as shown here:

  SELECT DISTINCT
   E.Employee,
   E.Manager,
   CASE WHEN M.Employee IS NULL THEN 0 ELSE 1 END As IsAManager  
 FROM
  Employee E LEFT OUTER JOIN Employee M
    ON E.Employee = M.Manager

Please note the following:

  • You did not specify the SQL product you're using, so I tried to make the solution general. I'm guessing from your attempt to use ISNULL that it's SQL Server, but this solution should work in any product that supports CASE.
  • Your method of storing manager status has one problem, which is that you cannot represent a manager with no employees (you derive the manager status from the existence of the employee-manager relationship). If you want to be able to store manager status separately from the employee-manager relationship then CREATE TABLE Managers (Employee. . . PRIMARY KEY). This will make the code necessary to get back manager status a little easier to write as well.
查看更多
登录 后发表回答