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

标签 arrays postgresql

我如何在 postgresql 中有效地总结/聚合这些数组,例如,我想要汇总 counts 列上从索引 2 到索引 6 的所有整数,并合并 null 或 missing 到 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}

最佳答案

您可以使用 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:

If the WITH ORDINALITY clause is specified, an additional column of type bigint will be added to the function result columns. This column numbers the rows of the function result set, starting from 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;

关于arrays - 如何为每个索引汇总一个整数数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34740015/

相关文章:

Java 2D 数组 : Return Row with Maximum Value

mysql - 结合 MYSQL 和 Postgresql

database - PostgreSQL 如何查看运行了哪些查询

SQL - 自连接以查找与第三个标签具有共同发布的两个标签

ruby - Heroku Rails 4 无法连接到服务器 : connection refused

json - 使用 Node.js 加载海量数据

javascript - 从数组中的对象中查找键的值 - Javascript

javascript - 使用 JQuery 从数组中设置选择选项值和文本

java - 比较数组中的连续元素并对相同值求和

php - 更新 json 数组的项