在Oracle中将此路径反转为z / y / x到x / y / z

时间:2009-09-04 19:57:19

标签: sql oracle plsql

如何在SELECT查询中反转此路径:

z/y/x 

代表

x/y/z

其中/是分隔符 并且在一行中可以有许多分隔符

ex: select (... z/y/x/w/v/u ...) reversed_path from ...

6 个答案:

答案 0 :(得分:7)

您可以通过连接还原的组件来获得结果,然后再次还原生成的字符串。只需确保剥离起始分隔符并将其放在另一侧:

SELECT '/' || REVERSE(LTRIM(SYS_CONNECT_BY_PATH(REVERSE(x), '/'), '/') AS reversed_path
...

答案 1 :(得分:4)

最简单的方法可能是编写一个存储的pl / sql函数,但是可以单独用SQL(Oracle)完成。

这将分解子路径中的路径:

SQL> variable path varchar2(4000);
SQL> exec :path := 'a/b/c/def';

PL/SQL procedure successfully completed
SQL> SELECT regexp_substr(:path, '[^/]+', 1, ROWNUM) sub_path, ROWNUM rk
  2    FROM dual
  3  CONNECT BY LEVEL <= length(regexp_replace(:path, '[^/]', '')) + 1;

SUB_P RK
----- --
a      1
b      2
c      3
def    4

然后,我们使用sys_connect_by_path

重构反向路径
SQL> SELECT MAX(sys_connect_by_path(sub_path, '/')) reversed_path
  2    FROM (SELECT regexp_substr(:path, '[^/]+', 1, ROWNUM) sub_path,
  3                 ROWNUM rk
  4             FROM dual
  5           CONNECT BY LEVEL <= length(regexp_replace(:path, '[^/]', '')) + 1)
  6  CONNECT BY PRIOR rk = rk + 1
  7   START WITH rk = length(regexp_replace(:path, '[^/]', '')) + 1;

REVERSED_PATH
-------------
/def/c/b/a

答案 2 :(得分:2)

你在寻找REVERSE吗? 即

SELECT REVERSE('z/y/x') FROM DUAL;

答案 3 :(得分:2)

找到另一个似乎灵活,精益的解决方案here,我觉得很容易理解:

    SELECT son_id,
           dad_id,
           son_name,
           SYS_CONNECT_BY_PATH (son_name, '/') AS family_path
      FROM (    SELECT son_id,
                       dad_id,
                       son_name,
                       CONNECT_BY_ISLEAF AS cbleaf
                  FROM family
            START WITH son_id IN (1, 2, 3, 4, 5)
            CONNECT BY PRIOR dad_id = son_id)
     WHERE CONNECT_BY_ISLEAF = 1
START WITH cbleaf = 1
CONNECT BY PRIOR son_id = dad_id

答案 4 :(得分:0)

@ Jean-Philippe Martin @OMG小马

尝试此查询,

SELECT REGEXP_SUBSTR(PATH,'[^/]+',1,4) || '/' || REGEXP_SUBSTR(PATH,'[^/]+',1,3) || '/' || REGEXP_SUBSTR(PATH,'[^/]+',1,2) || '/' || REGEXP_SUBSTR(PATH,'[^/]+',1,1) "Reverse of Path" 
  FROM (SELECT 'a/bc/def/ghij' PATH FROM DUAL);

我会这样做: - )

答案 5 :(得分:0)

select
    listagg(n.name,'\') within group (order by level desc)
 from nodes n
start with n.id = :childid
connect by prior n.parentid = n.id
order by level desc;

按级别描述。将首先在世系中连接祖先,因为您是从子代开始的