{{5,23}, {8,45}, {1,12}}
I want to sort this array by the first element of each submatrix element, for example:
{{ 1 ,12}, { 5 ,23}, { 8 ,45}}
How can i do this?
Edit:
This code works;
create or replace function arraysortingaccordingfirstindexofsubarrayelements() returns void as $$ declare samplearraydata integer[][]; declare sortedarraydata int[][]; begin samplearraydata:=ARRAY[[5,8], [1,6],[3,9]]; EXECUTE 'CREATE TEMP TABLE temptable ( firstindex integer, secondindex integer ) on commit drop;'; WITH data as (select samplearraydata as arr) insert into temptable select arr[i][1], arr[i][2] FROM data, generate_subscripts((SELECT arr FROM data), 1) i order by 1; sortedarraydata:=(SELECT array_agg_mult(ARRAY[ARRAY[y.firstindex, y.secondindex]])) FROM temptable y; raise notice '%', sortedarraydata; end; $$ language plpgsql; CREATE AGGREGATE array_agg_mult (anyarray) ( SFUNC = array_cat ,STYPE = anyarray ,INITCOND = '{}' ); CREATE TEMP TABLE arrtbl ( firstindex integer, secondindex integer ) on commit drop;
Credits for Erwin :)
sorting arrays sql database postgresql
cinfis Jun 15 '15 at 19:12 2015-06-15 19:12
source share