Oracle子串表基于层次结构

时间:2016-05-17 08:24:00

标签: sql oracle

我有一个字符串'1,2,3,4,5,6',我需要以表格格式输出

1,2,3,4,5,6-

1,2,3,4,5

1,2,3,4

1,2,3

1,2

1

1 个答案:

答案 0 :(得分:2)

查询 - 使用递归子查询分解子句

WITH table_name ( list ) AS (
  SELECT '1,2,3,4,5,6' FROM DUAL
),
rsqfc ( list ) AS (
  SELECT list FROM table_name
  UNION ALL
  SELECT SUBSTR( list, INSTR( list, ',', -1 ) -1 )
  FROM   rsqfc
  WHERE  INSTR( list, ',', -1 ) > 0
)
SELECT * FROM rsqfc;

查询 - 分层查询

WITH table_name ( list ) AS (
  SELECT '1,2,3,4,5,6' FROM DUAL
)
SELECT CASE LEVEL
            WHEN 1 THEN list
            ELSE SUBSTR( list, 1, INSTR( list, ',', -1, LEVEL - 1 ) - 1 )
            END AS list
FROM   table_name
CONNECT BY INSTR( list, ',', -1, LEVEL - 1 ) > 0;

<强>输出

(两者输出相同)

list
------------
1,2,3,4,5,6
1,2,3,4,5
1,2,3,4
1,2,3
1,2
1