我有下表:
Code ParentCode oItem
-----------------------------
A null Item 001
B A Item 002
C A Item 003
D C Item 004
E B Item 005
现在,我想要行号,结果应该是:
Rn Code ParentCode oItem
------------------------------------------
1 A null Item 001
2 B A Item 002
3 C A Item 003
4 D C Item 004
5 E B Item 005
我的问题是,如何获得以下结果的查询:
Rn Code RnParent ParentCode oItem
--------------------------------------------------------
1 A null null Item 001
2 B 1 A Item 002
3 C 1 A Item 003
4 D 3 C Item 004
5 E 2 B Item 005
如果您在结果表中看到,parentcode
实际上是code
,我需要知道id
基于parentcode
的{{1}} code
Rn
。
请告知。
谢谢。
答案 0 :(得分:1)
如果我理解正确,您只需要rn
parentcode
。您可以使用join
:
with t as (
select row_number() over (order by code) as rn, t.*
from t
)
select t.*, tp.rn as parentrn
from t left join
t tp
on t.parentcode = tp.code