Easiest way to find IsManager in SQL

早过忘川 提交于 2019-12-25 01:27:33

问题


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 :)


回答1:


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.




回答2:


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.


来源:https://stackoverflow.com/questions/7740258/easiest-way-to-find-ismanager-in-sql

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!