首页 > 解决方案 > 将相同长度的数组记录相加到新数组中

问题描述

我有一堆记录,每个记录都有一个数值数组。

这些值必须在数组中,因为在整个数据集中不能保证元素的数量是相同的,即我不能分成一致的列。

但是,每个数组的元素位置和长度的意义在一个“组”记录中是相同的,我需要对其进行聚合。

例如:

SELECT * FROM day_summary WHERE group_code=1;

summary_date | vals
-------------|--------
2019-04-17   | {0,3,4}
2019-04-18   | {1,3,2}
2019-04-19   | {7,5,1}

我需要汇总为:

SELECT extract('month' from summary_date) month,
    what_do_i_do(vals)
FROM day_summary
WHERE group_code=1
GROUP BY 1;

month  | vals
-------|--------
4      | {8,11,7}

(postgresql 9.6)

标签: sqlpostgresql

解决方案


如果你需要做很多,你可以为此创建一个自定义聚合:

create or replace function array_sum(p_one int[], p_two int[])
  returns int[]
as
$$
  select array_agg(coalesce(x1.val,0) + coalesce(x2.val,0))
  from unnest(p_one) with ordinality as x1(val, ix)
    full join unnest(p_two) with ordinality as x2(val, ix) on x1.ix = x2.ix;
$$
language sql
stable;

create aggregate array_sum_agg(int[]) 
(  
  sfunc = array_sum,
  stype = int[],
  initcond = '{}'
);

然后你可以像这样使用它:

SELECT extract('month' from summary_date) as month,
       array_sum_agg(vals)
FROM day_summary
WHERE group_code=1
GROUP BY 1;

在线示例:https ://rextester.com/XWD31187


推荐阅读