解析字符串“projects / project / 23”时可能会将其扩展为此结果:
projects
projects/project
projects/project/23
我想我可以使用滞后/引导窗口函数并进行此SQL查询:
select lag(unnest, 1, '') OVER () || '/' || unnest AS unnest
from unnest(string_to_array('projects/project/23', '/'))
但它不起作用。如何制作?
谢谢。
一个解决方案:
好的我找到了一个解决方案(但我觉得它不是最优的)
WITH t AS (
SELECT row_number() OVER (),
string_to_array('projects/project/23', '/')
FROM unnest(string_to_array('projects/project/23', '/'))
)
SELECT array_to_string(string_to_array[1:t.row_number], '/')
FROM t
答案 0 :(得分:0)
答案的主要部分 - 您需要使用string_agg滚动总计:
with cte as (
select a, row_number() over() as rn
from unnest(string_to_array('projects/project/23', '/')) as a
)
select string_agg(a, '/') over(order by rn)
from cte
它会起作用,但不保证元素的顺序(尽管我不能使查询工作错误)。要 100%保证元素顺序,您可以使用generate_subscripts函数:
with cte as (
select string_to_array('projects/project/23', '/') as a
), cte2 as (
select a, generate_subscripts(a, 1) as i from cte
)
select string_agg(a[i], '/') over(order by i)
from cte2