在Oracle sql中选择具有固定列的减号

时间:2017-06-21 11:39:06

标签: sql oracle

我想在两个表之间进行MINUS操作,如下所示:

表1:

employee_id |   job  | sector
----------- | ------ | ------
10          | a      | 1
10          | a      | 2
10          | b      | 4

表2:

job  | sector
---- | ------
a    | 1
a    | 2
a    | 3
b    | 1
b    | 4
c    | 1
c    | 2

因此我希望,对于每个employee_id,表1中没有连接{job,sector}。

结果:

employee_id | job | sector
----------- | --- | ------
10          | a   | 3
10          | b   | 1
10          | c   | 1
10          | c   | 2

有可能吗?

我希望我写得清楚!谢谢!

4 个答案:

答案 0 :(得分:1)

首先选择完整的数据集,即employee_id X作业/部门。从这些中删除现有的table1条目以获取缺少的条目。 (为了便于阅读,我已将您的表table2重命名为job_sector。我还假设您有employee表。)

select e.employee_id, js.job, js.sector
from employee e
cross join job_sector js
minus
select employee_id, job, sector
from table1;

答案 1 :(得分:0)

左连接,其中t2为空

select t1.*
from table1 t1
let join table2 t2
  on t1.job = t2.job
  and t1.sector = t2.sector
where t2.job is null

答案 2 :(得分:0)

这听起来只是一个left join(或not innot exists):

select 10 as employee_id, t2.*
from table2 t2 left join
     table1 t1
     on t2.job = t1.job and t2.sector = t1.sector
where t1.job is null;

如果表格未链接,我对如何获得员工ID 感到困惑。

如果t1中有多名员工,则可以执行以下操作:

select e.employee_id, t2.*
from (select distinct employee_id from t1) e cross join
     table2 t2 left join
     table1 t1
     on t2.job = t1.job and t2.sector = t1.sector and
        e.employee_id = t1.employee_id
where t1.job is null;

答案 3 :(得分:0)

您可以通过左连接来实现。您的查询将如下所示:

SELECT T2.*
FROM TABLE2 T2 LEFT JOIN
     TABLE1 T1
     ON T2.JOB = T1.JOB AND T2.SECTOR = T2.SECTOR
WHERE T1.JOB IS NULL;

虽然必须链接表才能获得员工ID。