您可以通过检测CODE列中定义父级级别的元素数量,并在PIVOT操作中使用它来获取各个层级的标题:
-- 示例数据:
WITH tbl AS
(
Select '1' as "CODE", 'abc' as "TITLE" From Dual Union All
Select '1-1' as "CODE", 'kkk' as "TITLE" From Dual Union All
Select '1-1-1' as "CODE", 'dfgf' as "TITLE" From Dual Union All
Select '1-1-1-1' as "CODE", 'dfsd' as "TITLE" From Dual Union All
Select '1-1-1-1-1' as "CODE", 'sdfsd' as "TITLE" From Dual Union All
Select '1-1-1-1-1-1' as "CODE", 'sccdfsd' as "TITLE" From Dual
)
-- SQL查询:
Select Max(TITLE_1) as "TITLE_1", Max(TITLE_2) as "TITLE_2", Max(TITLE_3) as "TITLE_3",
Max(TITLE_4) as "TITLE_4", Max(TITLE_5) as "TITLE_5", Max(TITLE_6) as "TITLE_6"
From (
Select CODE, TITLE, Length(CODE) - Length(Replace(CODE, '-')) + 1 as "LVL"
From tbl
)
PIVOT(Max(TITLE) For LVL IN(1 as "TITLE_1", 2 as "TITLE_2", 3 as "TITLE_3",
4 as "TITLE_4", 5 as "TITLE_5", 6 as "TITLE_6",
7 as "TITLE_7", 8 as "TITLE_8", 9 as "TITLE_9"))
Order By CODE
/* 结果:
TITLE_1 TITLE_2 TITLE_3 TITLE_4 TITLE_5 TITLE_6
------- ------- ------- ------- ------- -------
abc kkk dfgf dfsd sdfsd sccdfsd
*/
如果您想使用connect by,只需将内部SQL更改为如下所示:
Select Max(TITLE_1) as "TITLE_1", Max(TITLE_2) as "TITLE_2", Max(TITLE_3) as "TITLE_3",
Max(TITLE_4) as "TITLE_4", Max(TITLE_5) as "TITLE_5", Max(TITLE_6) as "TITLE_6"
From (
Select CODE, TITLE, LEVEL as "LVL"
From tbl
Where LEVEL = Length(CODE) - Length(Replace(CODE, '-')) + 1
Connect By LEVEL <= Length(CODE) - Length(Replace(CODE, '-')) + 1
)
PIVOT(Max(TITLE) For LVL IN(1 as "TITLE_1", 2 as "TITLE_2", 3 as "TITLE_3",
4 as "TITLE_4", 5 as "TITLE_5", 6 as "TITLE_6",
7 as "TITLE_7", 8 as "TITLE_8", 9 as "TITLE_9"))
Order By CODE
-- 结果与上述相同。