Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/arrays/14.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Sql postgres-如何基于和填充两个数组的新数组_Sql_Arrays_Postgresql - Fatal编程技术网

Sql postgres-如何基于和填充两个数组的新数组

Sql postgres-如何基于和填充两个数组的新数组,sql,arrays,postgresql,Sql,Arrays,Postgresql,我正在尝试使用AND like操作符比较两个数组,并在此基础上创建一个新数组。 请参见下面的示例,其中我有两个数组,一个是模板,其中包含空值和非空值(无论它们是什么,任何数字或字符串,关键是它们不为空),另一个是实际的数据数组 SELECT ARRAY[NULL, 1, NULL, 1, 1] as template; SELECT ARRAY[2, 3] as data; 我想创建一个新的数组,使用基于非空值的“模板”数组的“数据”数组填充该数组(模板数组中非空值的数量可能不同于数据数组,填

我正在尝试使用AND like操作符比较两个数组,并在此基础上创建一个新数组。 请参见下面的示例,其中我有两个数组,一个是模板,其中包含空值和非空值(无论它们是什么,任何数字或字符串,关键是它们不为空),另一个是实际的数据数组

SELECT ARRAY[NULL, 1, NULL, 1, 1] as template;
SELECT ARRAY[2, 3] as data;
我想创建一个新的数组,使用基于非空值的“模板”数组的“数据”数组填充该数组(模板数组中非空值的数量可能不同于数据数组,填充需要从左到右),因此结果如下所示:

{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) 

更多样本数据?。。我不明白最后一个1在哪里消失。。。