【发布时间】:2015-08-31 10:08:38
【问题描述】:
{{5,23}, {8,45}, {1,12}}
我想根据每个子数组元素的第一个元素对这个数组进行排序,比如;
{{<b>1</b>,12}, {<b>5</b>,23}, {<b>8</b>,45}}
我该怎么做?
编辑:
此代码有效;
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;
感谢欧文:)
【问题讨论】:
-
一如既往地,请使用您的 Postgres 版本。您是从表行中获取值还是只处理单个值?
-
@Erwin Brandstetter 9.4 我正在从表行中获取值...我将对每一行中的数组值进行排序,然后以排序方式对其进行更新。
标签: sql arrays database postgresql sorting