暂无图片
暂无图片
暂无图片
暂无图片
暂无图片

Oracle 将水平记录与垂直记录匹配

askTom 2017-03-10
319

问题描述

我有两个表table_a和table_b,结构如下

表 _ a
Emp_id号
部门编号

表 _ b
保持 _ 身份证号码
丢弃 _ 身份证号码
Dept_no编号

表 _ a
emp_id dept_no
101 10
102 10
103 20
108 10
107 20

表 _ b
保留id丢弃id dept_no
101 108 10
107 103 20

我的问题是
如何从table_A中获取相同Dept_no的Table_B的keep_id和discard_id列中存在的所有emp_id。

create table table_a(Emp_id号, dept_no number);

insert into  test_a values(102,10);
insert into  test_a values(103,20);
insert into  test_a  values(107,20);
insert into  test_a values(108,10);
insert into  test_a values(119,30);

commit;

create table test_b(keep_empid number, dicard_empid, dept_no);

insert into test_b values(101,108,10);
insert into test_b values(103,107,20);
insert into test_b values(110,187,10);

commit;
复制


结果应该如下所示

emp_id,dept_id
101,10
108,10
103,20
107,20
复制


专家解答

请在发布脚本之前先测试一下!那些 “创建表格” 不起作用...

你到底在找什么?

来自test_a的值,emp_ids等于部门的保留/丢弃值?
还是部门的保留/丢弃值之间的值?

无论是哪一个,你只需要加入:

create table test_a(emp_id number, dept_no number);

insert into  test_a values(102,10);
insert into  test_a values(103,20);
insert into  test_a  values(107,20);
insert into  test_a values(108,10);
insert into  test_a values(119,30);

commit;

create table test_b(keep_empid number, dicard_empid int, dept_no int);

insert into test_b values(101,108,10);
insert into test_b values(103,107,20);
insert into test_b values(110,187,10);

commit;

select a.* from test_a a
join   test_b b
on     b.dept_no = a.dept_no
and    (a.EMP_ID = b.keep_empid or a.emp_id = dicard_empid)
order  by 2, 1;

EMP_ID  DEPT_NO  
108     10       
103     20       
107     20   

select a.* from test_a a
join   test_b b
on     b.dept_no = a.dept_no
and    a.EMP_ID between b.keep_empid and dicard_empid
order  by 2, 1;

EMP_ID  DEPT_NO  
102     10       
108     10       
103     20       
107     20 
复制

「喜欢这篇文章,您的关注和赞赏是给作者最好的鼓励」
关注作者
【版权声明】本文为墨天轮用户原创内容,转载时必须标注文章的来源(墨天轮),文章链接,文章作者等基本信息,否则作者和墨天轮有权追究责任。如果您发现墨天轮中有涉嫌抄袭或者侵权的内容,欢迎发送邮件至:contact@modb.pro进行举报,并提供相关证据,一经查实,墨天轮将立刻删除相关内容。

评论