如何为每个索引汇总一个整数数组?

时间:2016-01-12 09:37:43

标签: arrays postgresql

如何在postgresql中有效地汇总/聚合这些数组,想要汇总从索引2到索引6,列counts和COALESCE null或缺少0的所有整数?

table_x:

ID       Counts
1        {1,    2,   null,  0,    null,   5,   8,   10}
2        {2,    5,   1,     null, 3}
3        {null, 3,   5,     0,    null,   8,   1}

To result:

Counts
{10,6,0,3,13}

1 个答案:

答案 0 :(得分:2)

您可以使用unnest获取每个元素,过滤索引从2到6,计算每个位置的总和,并使用array_agg将所有内容组合到一个数组中:

WITH cte AS
(
   SELECT pos, SUM(val::int) AS val
   FROM table_x
   ,LATERAL unnest(counts,ARRAY[1,2,3,4,5,6,7,8,9,10]) 
    AS sub(val, pos)
   WHERE pos BETWEEN 2 AND 6
   GROUP BY pos
)
SELECT array_agg(val ORDER BY pos) AS result
FROM cte;  

输出:

"{10,6,0,3,13}"

修改

根据评论中提出的@a_horse_with_no_name,您可以使用unnest with ordinality

  

如果指定了 WITH ORDINALITY 子句,则添加另一列   类型bigint将被添加到函数结果列中。这一栏   编号函数结果集的行,从1开始。

WITH cte AS
(
  SELECT pos, SUM(val::int) AS val
  FROM table_x
   ,LATERAL unnest(counts) with ordinality AS sub(val, pos)
  WHERE pos BETWEEN 2 AND 6
  GROUP BY pos
)
SELECT array_agg(val ORDER BY pos)
FROM cte;