替换二维数组中的元素

时间:2018-11-19 19:41:05

标签: postgresql postgresql-11

给出二维数组

select (ARRAY[[1,2,3], [4,0,0], [7,8,9]]);

{{1,2,3},{4,0,0},{7,8,9}}

是否可以用值5和6替换[2:2][2:]{{0,0}})处的切片? array_replace会替换一个特定的值,因此我不确定该如何处理。

1 个答案:

答案 0 :(得分:0)

我相信用plpgsql编写函数更易读。但是,也存在纯SQL解决方案: select ( select array_agg(inner_array order by outer_index) from ( select outer_index, array_agg( case when outer_index = 2 and inner_index = 2 then 5 when outer_index = 2 and inner_index = 3 then 6 else item end order by inner_index ) inner_array from ( select item, 1 + (n - 1) % array_length(a, 1) inner_index, 1 + (n - 1) / array_length(a, 2) outer_index from unnest(a) with ordinality x (item, n) ) _ group by outer_index )_ ) from ( select (ARRAY[[1,2,3], [4,0,0], [7,8,9]]) a )_;