0

I need split array by 2-pair portions, only nearby values. For example I have following array:

select array[1,2,3,4,5]

And I want to get 4 rows with following values:

{1,2}
{2,3}
{3,4}
{4,5}

Can I do it by SQL query?

1
  • I cannot imagine how to do it with raw sql - are you familiar with plpgsql? that should be your go-to tool for this, Commented Oct 2, 2017 at 16:18

2 Answers 2

1
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}
Sign up to request clarification or add additional context in comments.

3 Comments

@JackDouglas Good
also, might be best not to assume the ordering in the OPs sample array and use over(order by e)
0

One option is to do this with a recursive cte. Starting from the first position in the array and going up to the last.

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

a in the cte is the array.

Another option if you know the max length of the array is to use generate_series to get all numbers from 1 to max length and cross joining the array table on cardinality. Then use lead to get slices of the array and omit the last one (as lead on last row for a given partition would be null).

with nums(n) as (select * from generate_series(1,10))
select a,res 
from (select a,t.a[nums.n:lead(nums.n) over(partition by t.a order by nums.n)] as res
      from nums
      cross join t 
      where cardinality(t.a)>=nums.n
     ) tbl
where res is not null

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.