按二维数组的第一个元素排序

问题描述 投票:0回答:1

我正在尝试按第一个元素对每行的多维数组重新排序。

当前表:

id foobar
1 {{1.2,0.01}, {5.3, 0.05}, {3.5, 0.6}}

想要的桌子:

id foobar_重新排序
1 {{5.3, 0.05}, {3.5, 0.6}, {1.2,0.01}}

我是 sql 新手,但我认为我可以将数组取消嵌套到表中,然后按列排序并返回数组。我无法放入实际的表和列来创建输出表,但它适用于带有下面测试数组的代码。

取消表中数组的嵌套:

WITH data AS (
    SELECT t.aij_wij AS arr from public.pipe_aggr t
)
SELECT 
    arr[i][1] AS xi, 
    arr[i][2] AS wi
FROM 
    data, 
    generate_subscripts((SELECT arr FROM data), 1) i 

ERROR:  more than one row returned by a subquery used as an expression

取消数组与测试数组的嵌套:

WITH data AS (
    SELECT ARRAY[[1.2,0.01],[5.3, 0.05], [3.5,0.6]]::float8[] AS arr
)
SELECT 
    arr[i][1] AS xi, 
    arr[i][2] AS wi
FROM 
    data, 
    generate_subscripts((SELECT arr FROM data), 1) i
;
postgresql multidimensional-array
1个回答
0
投票

这按降序对第一维的数组进行排序(同时保留二维数组):

SELECT d.id, a.*
FROM   data d
LEFT   JOIN LATERAL (
   SELECT ARRAY(
      SELECT array_agg(d.foobar[d1][d2]) AS arr1
      FROM   generate_subscripts(d.foobar, 1) d1, generate_subscripts(d.foobar, 2) d2
      GROUP  BY d1
      ORDER  BY arr1 DESC
      )
   ) a(foobar_reorder) ON true;

参见:

© www.soinside.com 2019 - 2024. All rights reserved.