[英]Sql query for parent child records
我需要使用遞歸邏輯找出每個孩子的最終父記錄,直到找到父記錄為 null 例如 child=12 的最終父節點等於 7。因此,當我們遍歷找到最終父節點時,L1、L2 和L3 將填充在子記錄中。 我可以得到一些指導,我應該使用什么 SQL function 來生成以下 output。
輸入:
Child Parent L1 L2 L3
12 435 xyz
435 7 xyz abc def
7 Null xyz
Output:
Child L1 L2 L3
7 xyz
435 xyz abc def
12 xyz abc def
創建表語句:
CREATE TABLE mytable(
child NUMBER,
parent NUMBER,
l1 varchar2(3),
l2 varchar2(3),
l3 varchar2(3)
);
填充數據腳本:
insert into mytable(child, parent, l1, l2, l3)
values (12, 435, 'xyz', null, null);
insert into mytable(child, parent, l1, l2, l3)
values (435, 7, 'xyz', 'abc', 'def');
insert into mytable(child, parent, l1, l2, l3)
values (7, null, 'xyz', null, null);
我認為您想使用 connect by 來獲得正確的順序。 您可以使用 last value ignore nulls 子句獲取最后一個非 null 值。
SELECT child, parent,
last_value(l1) ignore nulls over (
order by level rows between unbounded preceding and current row
) l1,
last_value(l2) ignore nulls over (
order by level rows between unbounded preceding and current row
) l2,
last_value(l3) ignore nulls over (
order by level rows between unbounded preceding and current row
) l3
FROM mytable
START WITH child = 7
CONNECT BY PRIOR child = parent
您也可以在 sql 下方嘗試。 它適用於許多情況。
with cte (CHILD, PARENT, L1, L2, L3, temp_L1, temp_L2, temp_L3) as (
select CHILD, PARENT, L1, L2, L3
, L1 temp_L1, L2 temp_L2, L3 temp_L3
from mytable
where mytable.parent is null
union all
select t.CHILD, t.PARENT, t.L1, t.L2, t.L3
, nvl2(t.L1, t.L1, c.temp_L1)temp_L1
, nvl2(t.L2, t.L2, c.temp_L2)temp_L2
, nvl2(t.L3, t.L3, c.temp_L3)temp_L3
from mytable t
join cte c on t.parent = c.child
)
search depth first by child set order1
select CHILD, /*PARENT,*/ temp_L1 L1, temp_L2 L2, temp_L3 L3
from cte
order by order1
;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.