您好我有下表:
表格代码
A B C D
test 10 1 NEW
test2 1 5 NEW
test3 5 2 OLD
test4 40 3 NEW
test5 8 7 NEW
test6 7 9 OLDER
结果应该是
A B C D E
test 10 1 NEW OLD
test2 1 5 NEW OLD
test3 5 2 OLD
test4 40 3 NEW
test5 8 7 NEW OLDER
test6 7 9 OLDER
逻辑:
如果D为NEW,我检查C并查看该值是否在B中。如果没有,那就完成了那一行。 如果有一个条目,我检查D是否为NEW,如果是,如果新的C在另一行的B中,依此类推,直到我发现C值为B而D为NEW。 我不需要取这个值并把它放在受该saerch影响的其他行的D列中。
我有什么:
with CODE (A, B, C, D, E) AS
(SELECT Original.A, Original.B, Original.C, Original.D, ''
from myschema.basetable Original where Original.D = 'CORIPD'
UNION ALL
Select lookup.A, lookup.B, lookup.C, lookup.D, ''
from CODE Original, myschema.basetable lookup
where Original.A = lookup.A and Original.C = lookup.B
UNION ALL
Select lookup_next.A, lookup_next.B, lookup_next.C, '' D, lookup_next.D E
from CODE Original, myschema.basetable lookup_next
where Original.A = lookup_next.A and Original.C = lookup_next.B and lookup_next.C IS NULL
)
select A, B, C, D, E from CODE
order by A, C, D
到目前为止的结果:
A B C D E
test 10 1 NEW
test2 1 5 NEW
test3 5 2 OLD
test3 5 2 OLD
test4 40 3 NEW
test5 8 7 NEW
test6 7 9 OLDER
test6 7 9 OLDER
系统是Windows IBM DB2 10.5
感谢您提供的任何帮助。
答案 0 :(得分:0)
一种可能的解决方案 - 我在我的例子中使用了rectest作为表格ame
with temp (i,a,b,c,d,e) as (
select 1 as i, a,b,c,d, cast('-' as varchar(10)) as e
from rectest
where D <> 'NEW'
union all
select t.i + 1 as i, r.a, r.b, r.c, r.d
, case when t.i = 1 then t.d
when t.i > 1 and t.e <> '-' then t.e
else '-'
end as e
from temp t,
rectest r
where t.b = r.c
and t.i < 5
)
, temp2 as (
select a,b,c,d,e from temp
)
select * from temp2
union all
select a,b,c,d, '-' as e from rectest
where a not in (select a from temp2)
order by a;
第二个CTE只需要获取没有dependend行的行(这些行不属于recorsion - 在你的示例test4中。