3

表 EMP を使用します。ここで、MANAGER は従業員のマネージャーを表します。

EMPLOYEE   MANAGER
1          NULL
2          1
3          1
4          2
5          2

従業員がマネージャーかどうかを判断するクエリを作成するにはどうすればよいですか?

EMPLOYEE   STATUS
1          IS MANAGER
2          IS MANAGER
3          IS NOT MANAGER
4          IS NOT MANAGER
5          IS NOT MANAGER

サブクエリなしでこれを行うことは可能ですか?

4

3 に答える 3

3

You can JOIN the table on itself and use a CASE statement:

SELECT DISTINCT E.Employee, 
    CASE 
       WHEN M.Employee IS NOT NULL THEN 'IS MANAGER' 
       ELSE 'IS NOT MANAGER' END Status
FROM YourTable E
   LEFT JOIN YourTable M ON E.Employee = M.Manager

Use an OUTER JOIN to get all the employees and not just those that are managers.

于 2013-06-02T02:21:32.533 に答える
0

To get the list of manager primary keys, just

SELECT DISTINCT
    MANAGER
FROM 
    EMP;

To get more information about each manager assuming that the table also has such things as the manager's name:

SELECT DISTINCT
    m.employee, m.given_name, m.surname
FROM
    EMP m
JOIN
    EMP e
ON
    e.manager = m.employee;

I originally left out the manager's id, but I edited it to add it just in case the organization has two managers with the same name: John Smith, say.

If you want the status message, you can use a CASE call.

SELECT
    MANAGER,
    CASE COUNT(*)
        WHEN 0 THEN "IS NOT MANAGER"
        ELSE "IS MANAGER"
    END "STATUS"
FROM
    EMP
GROUP BY
    MANAGER;
于 2013-06-02T02:22:28.997 に答える
0

Short answer is no. Given the structure you show, there's no way of showing that without a join/subquery/CTE, you could know if the person is the top of the chain with:

SELECT *
FROM EMP 
WHERE MANAGER IS NULL

But aside from that you need a join/subquery/CTE.

于 2013-06-02T02:23:00.727 に答える