gpt4 book ai didi

arrays - 如何按位置对 postgresql 数组的元素求和?

转载 作者:行者123 更新时间:2023-11-29 12:52:53 24 4
gpt4 key购买 nike

假设我有一个返回生产作业表的查询,并且在一列中我有过去 7 天每个作业的输出数组:

 sku | job | outputs
-----------------------------
A1 | 123 | {2,4,6,5,5,5,5}
A1 | 135 | {0,0,0,3,5,7,9}
B3 | 109 | {3,2,3,2,3,2,3}
C5 | 144 | {5,5,5,5,5,5,5}

如何编写一个按 SKU(产品编号)分组并按位置对 7 天输出求和的查询?在这种情况下,您可以看到产品 A1 有两个生产作业:它们应该合并到结果的一行中:

 sku | outputs
--------------------------
A1 | {2,4,6,8,10,12,14}
B3 | {3,2,3,2,3,2,3}
C5 | {5,5,5,5,5,5,5}

最佳答案

您应该使用序数取消嵌套数组,按 sku 和序数计算分组中元素的总和,最后使用按 sku 分组的序数将总和聚合到数组中:

select sku, array_agg(elem order by ordinality) as outputs
from (
select sku, ordinality, sum(elem) as elem
from jobs
cross join unnest(outputs) with ordinality as u(elem, ordinality)
group by 1, 2
) s
group by 1
order by 1

DbFiddle.

如果您在各种情况下经常需要此功能,创建自定义聚合可能是合理的:

create or replace function sum_int_arrays(int[], int[])
returns int[] language sql immutable as $$
select array_agg(coalesce(a, 0)+ b)
from unnest($1, $2) as u(a, b)
$$;

create aggregate sum_int_array_agg(integer[]) (
sfunc = sum_int_arrays,
stype = int[]
);

select sku, sum_int_array_agg(outputs)
from jobs
group by 1
order by 1

DbFiddle.

关于arrays - 如何按位置对 postgresql 数组的元素求和?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49991371/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com