PostgreSQL中按部分拆分数组
我需要将数组拆分为2对部分,仅相邻的值。 例如,我有以下数组:PostgreSQL中按部分拆分数组,sql,postgresql,Sql,Postgresql,我需要将数组拆分为2对部分,仅相邻的值。 例如,我有以下数组: select array[1,2,3,4,5] 我想得到4行,值如下: {1,2} {2,3} {3,4} {4,5} 我可以通过SQL查询来完成吗?一个选项是使用递归cte来完成。从阵列中的第一个位置开始,一直到最后一个位置 with recursive cte(a,val,strt,ed,l) as (select a,a[1:2] as val,1 strt,2 ed,cardinality(a) as l from
select array[1,2,3,4,5]
我想得到4行,值如下:
{1,2}
{2,3}
{3,4}
{4,5}
我可以通过SQL查询来完成吗?一个选项是使用递归cte来完成。从阵列中的第一个位置开始,一直到最后一个位置
with recursive cte(a,val,strt,ed,l) as
(select a,a[1:2] as val,1 strt,2 ed,cardinality(a) as l
from t
union all
select a,a[strt+1:ed+1],strt+1,ed+1,l
from cte where ed<l
)
select val from cte
一种选择是使用递归cte来实现这一点。从阵列中的第一个位置开始,一直到最后一个位置
with recursive cte(a,val,strt,ed,l) as
(select a,a[1:2] as val,1 strt,2 ed,cardinality(a) as l
from t
union all
select a,a[strt+1:ed+1],strt+1,ed+1,l
from cte where ed<l
)
select val from cte
我无法想象如何使用原始sql—您熟悉plpgsql吗?这应该是您的首选工具,我无法想象如何使用原始sql实现它-您熟悉plpgsql吗?这应该是你的工具,或者@JackDouglas Goodall,最好不要在OPs样本数组中进行排序并使用
over(按e排序)
或者@JackDouglas Goodall,最好不要在OPs样本数组中进行排序并使用over(按e排序)
select a
from (
select array[e, lead(e) over()] as a
from unnest(array[1,2,3,4,5]) u(e)
) a
where not exists (
select 1
from unnest(a) u (e)
where e is null
);
a
-------
{1,2}
{2,3}
{3,4}
{4,5}