1

I'm trying to turn a 1d jsonb array

[1, 2]

into 2d array where its elements are repeated 3 times (the result can be in jsonb)

[[1, 1, 1],
 [2, 2, 2]]

My attempt doesn't work

select array(select array_fill(a::text::integer, array[3])) 
  from jsonb_array_elements('[1,2]'::jsonb) as a;

ERROR:  could not find array type for data type integer[]

Maybe it would work in later PG version, but I'm restricted to PG 9.4.8

What are the other ways?

ave
  • 18,083
  • 9
  • 30
  • 39

1 Answers1

4

First of all, you need to replace array() with array_agg(), then you'll have what you expect, starting with Postgres 9.5.

That being said, your issue is with array_agg() not being able to aggregates arrays prior to 9.5.

Then are multiple existing answers for you, but basically you'll need to create a new aggregate function array_agg_mul:

CREATE AGGREGATE array_agg_mult (anyarray)  (
    SFUNC     = array_cat,
    STYPE     = anyarray,
    INITCOND  = '{}'
);

then running the following query should work:

SELECT
    array_agg_mult(array[array_fill(a::text::integer, array[3])])
FROM jsonb_array_elements('[1,2]'::jsonb) as a;

Then you should get:

  array_agg_mult
-------------------
 {{1,1,1},{2,2,2}}
Community
  • 1
  • 1
fpietka
  • 1,027
  • 1
  • 10
  • 23