sql - 将相同长度的数组记录相加到新数组中
问题描述
我有一堆记录,每个记录都有一个数值数组。
这些值必须在数组中,因为在整个数据集中不能保证元素的数量是相同的,即我不能分成一致的列。
但是,每个数组的元素位置和长度的意义在一个“组”记录中是相同的,我需要对其进行聚合。
例如:
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)
解决方案
如果你需要做很多,你可以为此创建一个自定义聚合:
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;
推荐阅读
- python - 我想用 csv 模块替换熊猫
- powershell - 如何获取服务器列表以及该应用程序的相应应用程序和版本以正确导出到 Excel 中?
- python - 总数 scikit-learn 中的迭代次数达到极限
- azure - Azure 函数中的 Azure 广告集成与招摇
- javascript - 即使在回调中定义变量后,变量也未定义
- python - 如何使用不同的模块导入运行相同的 python 脚本?
- domain-driven-design - 聚合不变量
- c++ - 使用 Bisonc++ 跳过 Parser::lex() 方法预定义
- python - 根据索引位置将多行插入数据框中
- java - 如何从 json 结果集中获取状态?