我有下表(表1是基表),我需要派生一个新字段“ catid”和“ origid”。 “ Catid”只是(id和nv)的串联,但是origid是通过检查表1中是否存在表2中的(sid或sid2或sid3或sid4)而得出的。如果存在它们,只需将table1中的“ catid”分配给他们
具有表1:
id nv sid sid2 sid3 sid4
---------------------------------------
1 a 11 A1 B1 C1
2 b 22 A2 B2 (null)
3 c 33 A3 B3 C3
表2:
id nv sid sid2 sid3 sid4
---------------------------------------
4 x 11 (null) B1 C1
5 y (null) A2 B2 (null)
6 z 33 A3 (null) C3
要表3:
id nv sid sid2 sid3 sid4 catid origid
--------------------------------------------------
1 a 11 A1 B1 C1 1a 1a
2 b 22 A2 B2 (null) 2b 2b
3 c 33 A3 B3 C3 3c 3c
4 x 11 (null) B1 C1 4x 1a
5 y (null) A2 B2 (null) 5y 2b
6 z 33 A3 (null) C3 6z 3c
表1
create table table1 (
id number,
nv varchar2(2)
sid varchar2(3),
sid2 varchar2(3),
sid3 varchar2(3),
sid4 varchar2(3)
);
Table 2
create table table2 (
id number,
nv varchar2(2),
sid varchar2(3),
sid2 varchar2(3),
sid3 varchar2(3),
sid4 varchar2(3)
);
insert into table1 values(1, 'a', '11','A1','B1','C1');
insert into table1 values(2, 'b', '22','A2','B2','');
insert into table1 values(3, 'c', '33','A3','B3','C3');
insert into table2 values(4, 'x', '11','','B1','C1');
insert into table2 values(5, 'y', '','A2','B2','');
insert into table2 values(6, 'z', '33','A3','','C3');
谢谢
答案 0 :(得分:0)
您需要某种join
来执行此操作。这是一种方法:
with t1 as (
select id, nv, sid, sid2, sid3, sid4,
id || nv as catid, id || nv as origid
from table1
)
select id, nv, sid, sid2, sid3, sid4, catid, origid
from t1
union all
select id, nv, sid, sid2, sid3, sid4, id || nv as catid,
(select t1.origid
from t1
where (t1.sid = t2.sid or t1.sid2 = t2.sid2 or
t1.sid3 = t2.sid3 or t1.sid4 = t2.sid4
) and
rownum = 1
) as origid
from table2 t2;
Here是db <>小提琴。