【问题标题】:postgres rows to 2 dimensional arraypostgres 行到二维数组
【发布时间】:2013-05-27 11:08:47
【问题描述】:

是否有任何简单的方法可以将 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 函数来执行此操作?有什么建议吗?

【问题讨论】:

    标签: postgresql multidimensional-array


    【解决方案1】:

    这是我为 LedgerSMB 所做的:

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

    那么你可以:

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

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

    【讨论】:

    【解决方案2】:
    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
    

    【讨论】:

    • 基于现有 PostgreSQL 函数创建聚合要容易得多;-)
    【解决方案3】:
    select array_agg(ARRAY[foo,bar]) from foobar
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-07-23
      • 2013-11-23
      • 1970-01-01
      • 2018-07-17
      相关资源
      最近更新 更多