2

有没有简单的方法将 postgres 表转换为二维?

我有一个数据表 foobar 有两列 foo 和 bar 在 1,2 3,4 5,6 中有以下数据

我想把它转换成

{ 
{1,2},
{3,4},
{5,6}
}

我尝试过类似的事情

从 foobar 中选择 ARRAY[foo,bar]

这创造了

{1,2}
{3,4}
{5,6}

几乎在那里

我怀疑我将不得不编写 pgpsql 函数来做到这一点?有什么建议么?

4

3 回答 3

2

这是我为 LedgerSMB 所做的:

CREATE AGGREGATE compound_array (
        BASETYPE = ANYARRAY,
        STYPE = ANYARRAY,
        SFUNC = ARRAY_CAT,
        INITCOND = '{}'
);

那么你也能:

select compound_array(ARRAY[[foo,bar]]) from foobar;

请注意,您需要有两对方括号,否则它只会将它们添加到一维数组中。

于 2013-06-08T10:43:10.467 回答
1
create or replace function my_array()
returns integer[] as $function$
declare
    r record;
    a integer[];
begin

    for r in 
        select foo, bar
        from (values
            (1, 2), (3, 4), (5, 6)
        ) foobar (foo, bar)
    loop
        a := a || array[[r.foo, r.bar]];
    end loop;

    return a;

end;
$function$ language plpgsql;

select my_array();
      my_array       
---------------------
 {{1,2},{3,4},{5,6}}

select (my_array())[2][2];
 my_array 
----------
        4
于 2013-05-27T12:19:42.840 回答
1
select array_agg(ARRAY[foo,bar]) from foobar
于 2020-01-08T13:33:00.380 回答