SYS_CONNECT_BY_PATH 和 START WITH/CONNECT BY PostgreSQL 等效项

B J*_*B J 2 oracle postgresql

我有一个查询,它是用 Oracle 编写的一个更大查询的一部分,我需要将其转换为 PostgreSQL。

/*rn and cnt are defined earlier*/
SELECT wtn, LTRIM(SYS_CONNECT_BY_PATH(RESP_TCSI, ','),',') TCSI_CODES
FROM DATA
WHERE rn = cnt
START WITH rn = 1
CONNECT BY PRIOR rn = rn-1
AND PRIOR WTN = WTN
Run Code Online (Sandbox Code Playgroud)

据我所知,SYS_CONNECT_BY_PATH()Postgres 中没有类似的东西。我知道 PostgresCONNECTBY()在 tablefunc 中有一个函数,但我不认为它执行 start with 和 connect by bits 的功能。我也知道 Postgres 相当于什么LTRIM(),但如果我必须使用CONNECTBY()或类似的东西,我不确定修剪字符串是否重要。

阅读和搜索周围我注意到可能有一种方法可以通过一些递归选择来做到这一点,但我不确定我将如何做到这一点,除此之外,我真的不明白代码在做什么。我的假设是它与基于 Oracle 等效项的分层树有关,但即便如此我也不确定。我如何在 Postgres 中做与此等效或类似的事情?

谢谢。

小智 6

使用递归公用表表达式

with recursive tree as (
  select wtn, 
         resp_tcsi as tcsi_codes
   from data
   where rn = 1 -- this is the "start with" part

   union all

   select ch.wtn, 
          p.tcsi_codes||','||ch.resp_tcsi 
   from data as ch
    join tree p 
      on ch.rn -1 = p.rn -- this is the "connect by" part
     and ch.wtn = p.wtn
)
select *
from tree;
Run Code Online (Sandbox Code Playgroud)