我正在尝试通过使用类似 AND 的运算符比较两个数组来创建一个新数组。 请参见下面的示例,其中我有两个数组,一个是 template,其中包含 NULL 和 NON-NULL 值(无论它们是什么,任何数字或字符串,关键是它们不为空),另一个是实际的数据数组。
SELECT ARRAY[NULL, 1, NULL, 1, 1] as template;
SELECT ARRAY[2, 3] as data;
我想创建一个新数组,我根据"template"数组填充“数据”数组,其中存在非空值(模板数组中非空值的数量可能与此不同数据数组,填充需要从左到右),因此结果将如下所示:
{NULL,2,NULL,3,NULL}
有没有人做过类似的事情?
最佳答案
通常最简单的数组操作方法是 plpgsql 函数,例如:
create or replace function fill_array_from_template(template anyarray, data anyarray)
returns anyarray language plpgsql as $$
declare
i int;
n int = 1;
begin
for i in 1..array_length(template, 1) loop
if template[i] is not null then
template[i] := data[n];
n:= n+ 1;
end if;
end loop;
return template;
end $$;
select fill_array_from_template(array[null, 1, null, 1, 1], array[2, 3]);
fill_array_from_template
--------------------------
{NULL,2,NULL,3,NULL}
(1 row)
关于sql - postgres - 如何根据两个数组的 AND 填充一个新数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45816602/