SQL select 有多个不同的条件

SQL select with multiple different conditions

我还在学习SQL,找不到合适的方法来查找以下信息:

我创建了一个 table "employees" 包含以下列:

'department'、'age'、'salary'、'bonus';

我正在尝试设计一个查询,该查询将向我提供另一个部门中与他们年龄相同且奖金高于其薪水的所有员工。

(更准确地说,如果部门'SALES'的某人与部门'RESEARCH'的某人年龄相同,并且奖金比研究人员的薪水高,那么我会喜欢同时展示它们)

这可以在 sql 中完成吗?

感谢您的宝贵时间,

-汤姆

您可以使用 exists 执行此操作。因为你关心的是两个方向的关系,这个就简单了,找两个部门同龄但奖金不一样的人:

select e.*
from employees e
where exists (select 1
              from employees e2
              where e2.department <> e.department and e2.age = e.age and
                    e2.bonus <> e.bonus
             );

要获得同一行的对,请使用自连接:

select e1.*, e2.*
from employees e1 join
     employees e2
     on e1.age = e2.age and e1.department <> e2.department and
        e1.bonus > e2.bonus;