甲骨文設置:
CREATE TABLE your_table (Id, SUm, Tree_path_structure) AS
SELECT 1, 10, '/1/2' FROM DUAL UNION ALL
SELECT 2, 30, '/1/3/4' FROM DUAL UNION ALL
SELECT 3, 40, '/1/3/5' FROM DUAL UNION ALL
SELECT 4, 50, '/1/6' FROM DUAL;
查詢:
SELECT id,
sum,
tree_path_structure
FROM (
SELECT id,
sum,
tree_path_structure,
CASE
WHEN is_Max_Depth = 0
OR sum = MIN(sum) OVER (PARTITION BY is_Max_Depth)
THEN 0
ELSE 1
END AS is_Max_Depth_With_Higher_sum
FROM (
SELECT id,
sum,
tree_path_structure,
CASE depth WHEN MAX(depth) OVER() THEN 1 ELSE 0 END AS is_Max_Depth
FROM (
SELECT ID,
SUM,
Tree_Path_Structure,
LENGTH(Tree_Path_Structure) - LENGTH(REPLACE(Tree_Path_Structure, '/'))
AS depth
FROM your_table
) t
)
)
WHERE is_Max_Depth_With_Higher_sum = 0;
輸出:
ID SUM TREE_P
---------- ---------- ------
1 10 /1/2
4 50 /1/6
2 30 /1/3/4
更新:
SELECT id,
sum,
tree_path_structure
FROM (
SELECT id,
sum,
tree_path_structure,
CASE
WHEN is_Max_Depth = 0
OR sum = MIN(sum) OVER (PARTITION BY root, is_Max_Depth)
THEN 0
ELSE 1
END AS is_Max_Depth_With_Higher_sum
FROM (
SELECT id,
sum,
tree_path_structure,
root,
CASE depth WHEN MAX(depth) OVER (PARTITION BY root) THEN 1 ELSE 0 END AS is_Max_Depth
FROM (
SELECT ID,
SUM,
Tree_Path_Structure,
SUBSTR(Tree_Path_Structure, 1, INSTR(Tree_Path_Structure, '/', 1, 2))
AS root,
LENGTH(Tree_Path_Structure) - LENGTH(REPLACE(Tree_Path_Structure, '/'))
AS depth
FROM your_table
) t
)
)
WHERE is_Max_Depth_With_Higher_sum = 0;
謝謝!如果我有多個樹形路徑,並不是所有的樹都在第一層,就像下面的數據一樣。 CREATE TABLE your_table(Id,SUm,Tree_path_structure)AS SELECT 1,10,'/ 1/2'FROM DUAL UNION ALL SELECT 2,30,'/ 1/3/4'FROM DUAL UNION ALL SELECT 3,40,'/ 1/3/5'來自雙聯所有選擇4,50,'/ 1/6'來自雙聯所有選擇5,10,'/ 7/8/9'來自雙聯所有選擇6,15,'/ 7/10/11'FROM DUAL; –
感謝您的查詢更新。但是,如果查詢應該返回基於樹和樹級別長度的min(sum)值。 –
CREATE TABLE your_table(ID,SUM,Tree_path_structure)AS SELECT 1,10- \t \t, '/ 1' FROM DUAL UNION ALL \t SELECT \t \t 2,20, '/ 1/2' FROM DUAL UNION ALL \t SELECT \t \t 3,10, '/ 1/3' FROM DUAL UNION ALL \t SELECT \t \t 4,30, '/ 1/2/4' \t FROM DUAL UNION ALL \t SELECT \t \t 5,15,'/ 1/2/5'\t FROM DUAL UNION ALL \t SELECT \t 6,40 \t, '/ 1/3/6' FROM DUAL UNION ALL \t SELECT \t \t 7,22, '/ 7' \t FROM DUAL UNION ALL \t SELECT \t \t 8,50, '/ 7/8' FROM DUAL UNION ALL \t 選擇\t 9,60 \t, '/ 7/8/9' FROM DUAL UNION ALL \t 選擇\t 10,19, '/ 10年7月8日' \t FROM DUAL UNION ALL \t 選擇\t 11,15 ,'/ 7/8/11'\t FROM DUAL UNION ALL \t SELECT \t 12,13'/ 7/8/12'\t FROM DUAL; –