我有一个如下所示的分层表。我想FLAG
根据CODE
值设置属性。可能的代码值为R
、NR
和。将设置为iff 对应的 code 值与 parent 的一致 ieRN
NF
FLAG
'Y'
if parent.code = 'R' and child.code = 'R' then flag = 'Y'
if parent.code = 'NR' and child.code = 'NR' then flag = 'Y'
if parent.code = 'RNR' and child.code = 'R' or 'NR', then flag = 'Y'.
这是我的桌子:
create table My_BOM(assign_Id varchar2(50) not null primary key,
parent_assign_Id varchar2(50) references My_BOM(assign_Id),
code varchar2(50) not null,
flag varchar2(1) default 'Y');
insert into my_bom values ('T1',null,'RNR','Y');
insert into my_bom values ('T2','T1','R','Y');
insert into my_bom values ('T3','T2','NR','Y');
insert into my_bom values ('T4','T3','R','Y');
insert into my_bom values ('T5','T1','NF','Y');
insert into my_bom values ('T6','T5','R','Y');
insert into my_bom values ('T7','T1','NR','Y');
insert into my_bom values ('T8','T7','RNR','Y');
insert into my_bom values ('T9','T8','R','Y');
insert into my_bom values ('T10','T1','RNR','Y');
如何设置FLAG?这就是我尝试过的方式,但是这个查询也返回了我不想要的 T9 记录,因为链在两者之间断开,即它们在CODE
. 所以,T9 不应该是结果的一部分。
select connect_by_root(assign_Id), assign_Id desc_assign_Id, code, flag
from my_bom
where
--exists (select null from my_bom mb where mb.parent_assign_Id = prior my_bom.assign_Id
--connect by mb.parent_assign_Id = prior mb.assign_Id) and
DECODE( CODE,
'R', 'R', 'NR', 'NR', 'RNR',
:bind_var, NULL) = PRIOR DECODE( CODE,
'R', 'R', 'NR', 'NR', 'RNR',
:bind_var, NULL)
start with parent_assign_Id is null
connect by parent_assign_Id = prior assign_Id
order by desc_assign_Id;
"bind_var"
将是'R'
或 'NR'
这是 SQL 小提琴:http ://sqlfiddle.com/#!4/009ad/2/0