1

解析字符串“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
4

1 回答 1

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

sql fiddle demo

它会起作用,但不能保证元素的顺序(尽管我不能使查询出错)。要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

sql fiddle demo

于 2013-09-08T07:51:59.750 回答