SQL Server 员工收入高于任何管理人员

hsvhsicv  于 2023-01-16  发布在  其他
关注(0)|答案(5)|浏览(96)

我有一张table:

+----+-------+--------+-----------+
| Id | Name  | Salary | ManagerId |
+----+-------+--------+-----------+
| 1  | Joe   | 70000  | 3         |
| 2  | Henry | 80000  | 4         |
| 3  | Sam   | 60000  | NULL      |
| 4  | Max   | 90000  | NULL      |
+----+-------+--------+-----------+

我需要让员工比任何经理都挣得多
我创建了一个查询,我得到的雇员谁的收入比他们的经理:

select a.Name
from Employee a inner join Employee b on a.ManagerId = b.Id
where a.Salary > b.Salary

如何修改此查询以获取多个管理器?

oxiaedzo

oxiaedzo1#

你不需要任何加入。获得所有经理的最高工资,并检查员工工资是否大于经理的最高工资

select a.Name
from Employee a 
where a.Salary > 
(SELECT MAX(salary) FROM Employee m WHERE m.id IN (SELECT managerID FROM Employee))--or however you determine managers
qoefvg9y

qoefvg9y2#

您可以使用EXISTS来代替:

SELECT E.[Name]
FROM dbo.Employee E
WHERE EXISTS (SELECT 1
              FROM dbo.Employee E2
                   JOIN dbo.Employee M ON E2.ManagerID = M.id
              WHERE M.Salary < E.Salary);

不过EXISTS有点乱,因为判断某人是否是经理的唯一方法是某人是否让他们担任经理。

kpbpu008

kpbpu0083#

如果要使用联接而不是子查询:

SELECT DISTINCT a.Name
FROM Employee a
CROSS JOIN Employee b 
WHERE a.Salary > b.Salary and b.Manager ID IS NULL
qvk1mo1f

qvk1mo1f4#

获得比任何经理都多的
表示您希望员工的收入高于经理的最低薪金:

select name from employees 
where salary > ( 
  select min(salary) from employees
  where id in (select distinct managerid from employees)
)

select name from employees 
where salary > ANY ( 
  select salary from employees
  where id in (select distinct managerid from employees)
)

如果只希望非经理的员工使用CTE:

with cte as (select distinct managerid from employees)
select name from employees 
where 
  id not in cte
  and 
  salary > (select min(salary) from employees where id in cte)
fhg3lkii

fhg3lkii5#

SELECT *
FROM employees e,
  (SELECT *
   FROM employees
   WHERE emp_id IN
       (SELECT manager_id
        FROM employees)) a
WHERE e.salary >a.salary
  AND e.manager_id = a.emp_id;

相关问题