在 psql 中创建 "counter" 数组

Create "counter" array in psql

我在 postgresql-9.4.2 中有一个带有数组列的 table。

create schema test_schema;
create table test_schema.test_table;
(
    array_column int[]
);
insert into test_schema.test_table values
    (ARRAY[5,12,6,2]),
    (ARRAY[51,4,2]),
    (ARRAY[2]),
    (ARRAY[3,16]);

看起来像这样

    | array_column |
    | integer[]    |
--------------------
  1 | {5,12,6,2}   |
  2 | {51,4,2}     |
  3 | {2}          |
  4 | {3,16}       |

我想查询这个 table,并在我的查询中添加一列,这是一个从 1 到数组大小的数组。

我已经想出如何创建一个相同大小的数组,如下所示

select
    array_column,
    array_fill(1,array[array_length(array_column,1)],array[1]) as counter
from
    test_schema.test_table;

其中returns以下结果

    | array_column | counter    |
    | integer[]    | integer[]  |
---------------------------------
  1 | {5,12,6,2}   | {1,1,1,1}  |
  2 | {51,4,2}     | {1,1,1}    |
  3 | {2}          | {1}        |
  4 | {3,16}       | {1,1}      |

我打算计算计数器的滚动总和,这会给我想要的结果,但我不知道该怎么做。

这是期望的结果:

    | array_column | counter    |
    | integer[]    | integer[]  |
---------------------------------
  1 | {5,12,6,2}   | {1,2,3,4}  |
  2 | {51,4,2}     | {1,2,3}    |
  3 | {2}          | {1}        |
  4 | {3,16}       | {1,2}      |

感谢您的帮助

使用函数generate_subscripts(array anyarray, dim int):

select
    array_column,
    array_agg(subscripts) subscripts
from (
    select
        array_column, 
        generate_subscripts(array_column, 1) subscripts
    from
        test_schema.test_table
    ) sub
group by 1;

 array_column | subscripts 
--------------+------------
 {2}          | {1}
 {3,16}       | {1,2}
 {5,12,6,2}   | {1,2,3,4}
 {51,4,2}     | {1,2,3}
(4 rows)
select array_column, a
from
    test_table
    cross join lateral (
        select array_agg(a)
        from generate_series(1, array_length(array_column, 1)) s(a)
    ) s(a)
;