我如何在 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/