有了充分肯定Pablomatico爲起點,看看這個擴張他的工作是包括對不是2位數字的ID處理,並重新加入到源帶回剛剛纔根排的屬性:
WITH the_table AS (SELECT 'W0' item_id, NULL parent_id, 'Red' colour FROM DUAL
UNION
SELECT 'W1' item_id, 'W0' parent_id , 'blue' colour FROM DUAL
UNION
SELECT 'W2' item_id, 'W1' parent_id, 'Grey' colour FROM DUAL
UNION
SELECT 'W3' item_id, 'W1' parent_id, 'Black' colour FROM DUAL
UNION
SELECT 'W4' item_id, 'W3' parent_id, 'Mauve' colour FROM DUAL
UNION
SELECT 'W5' item_id, 'W4' parent_id, 'Orange' colour FROM DUAL
UNION
SELECT 'W6' item_id, 'W0' parent_id, 'Green' colour FROM DUAL
UNION
SELECT 'W7' item_id, 'W6' parent_id, 'Grey' colour FROM DUAL
UNION
SELECT 'W8' item_id, 'W0' parent_id, 'Pink' colour FROM DUAL)
SELECT main_tab.item_id, main_tab.colour,main_tab.just_before_root, the_Table.colour
FROM
(SELECT item_id,
colour,
SYS_CONNECT_BY_PATH(item_id, '/') node_path,
CASE WHEN INSTR(SYS_CONNECT_BY_PATH(item_id, '/'),'/',1,2) = 0 THEN NULL
WHEN INSTR(SYS_CONNECT_BY_PATH(item_id, '/'),'/',1,2) != 0
AND INSTR(SYS_CONNECT_BY_PATH(item_id, '/'),'/',1,3) = 0
THEN SUBSTR(SYS_CONNECT_BY_PATH(item_id, '/'), INSTR(SYS_CONNECT_BY_PATH(item_id, '/'),'/',1,2)+1)
ELSE SUBSTR(SYS_CONNECT_BY_PATH(item_id, '/'), INSTR(SYS_CONNECT_BY_PATH(item_id, '/'),'/',1,2)+1,INSTR(SYS_CONNECT_BY_PATH(item_id, '/'),'/',1,3) - INSTR(SYS_CONNECT_BY_PATH(item_id, '/'),'/',1,2) - 1) END just_before_root
FROM the_table
CONNECT BY PRIOR item_id = parent_id
START WITH parent_id IS NULL) main_tab
left outer join the_table on main_tab.just_before_root = the_table.item_id;
返回:
ITEM_ID COLOUR JUST_BEFORE_ROOT COLOUR_1
"W0" "Red"
"W1" "blue" "W1" "blue"
"W2" "Grey" "W1" "blue"
"W3" "Black" "W1" "blue"
"W4" "Mauve" "W1" "blue"
"W5" "Orange" "W1" "blue"
"W6" "Green" "W6" "Green"
"W7" "Grey" "W6" "Green"
"W8" "Pink" "W8" "Pink"
無採樣數據/表給出一個簡單的查詢,我可能會建議你看SYS_CONNECT_BY_PATH,然後解析它以返回null,如果爲null(W0),則其自身(如果路徑中只有一個節點(W1),或者默認爲第二個節點(Root + 1))返回所有其他情況。 –
@MichaelBroughton我明白你的想法是什麼,但我認爲它不適用於我的情況。我在我的問題中添加了一些細節以使其更易於理解 – Vizul