繁体   English   中英

将数组项提取到不同列的功能PostgreSQL

[英]Function to extract array items to different columns postgresql

我正在尝试设计一个函数来解决此问题。 我有一些类似这样的城市专栏。

1 |Curaçao-Amsterdam
2 |St. Christopher-Essequibo
3 |Texel-Riohacha-Buenos Aires-La Rochelle`

我已经使用此查询将其提取到元素数组中

select t2.rut1,t2.rutacompleta, t2.id 
from (
   select regexp_split_to_array(t.rutacompleta, E'[\-]+') as rut1, 
          t.rutacompleta,t.id 
   from (
      select id, strpos(ruta, '-') as posinic, strpos(ruta, '-') as posfin,
      ruta as rutacompleta 
      from dyncoopnet.todosnavios2
    ) t
) t2

得出以下结果:

 {Curaçao,Amsterdam} {"St. Christopher",Essequibo} {Texel,Riohacha,"Buenos Aires","La Rochelle"}` 

我想创建一个函数来提取*数组元素到不同的列。 我想到了这样的一会儿功能:

create or replace function extractpuertos()
returns text as
$body$
declare
i integer;
puerto text;
begin
i := 1
while (i >=1)
loop
with tv as(
select t2.rut1,t2.rutacompleta, t2.id from(
select regexp_split_to_array(t.rutacompleta, E'[\-]+') as rut1, 
t.rutacompleta,t.id from(
select id, strpos(ruta, '-') as posinic, strpos(ruta, '-') as posfin,ruta as 
rutacompleta from dyncoopnet.todosnavios2) t)t2 
)
select tv.rut1[i] as puerto from tv;
end loop;
return puerto;
end;

但我不确定这是否是正确的解决方案以及如何实施。 有什么提示吗? 提前致谢!

这是您尝试做的吗?

创建表:

t=# create table so65 (i int, t text);
CREATE TABLE
Time: 55.234 ms

填充数据:

t=# copy so65 from stdin delimiter '|';
Enter data to be copied followed by a newline.
End with a backslash and a period on a line by itself.
>> 1 |Curaçao-Amsterdam
2 |St. Christopher-Essequibo
3 |Texel-Riohacha-Buenos Aires-La Rochelle>> >>
>> \.
COPY 3
Time: 2856.465 ms

分裂:

t=# select string_to_array(t,'-') from so65;
                string_to_array
-----------------------------------------------
 {Curaçao,Amsterdam}
 {"St. Christopher",Essequibo}
 {Texel,Riohacha,"Buenos Aires","La Rochelle"}
(3 rows)

Time: 4.428 ms

到一栏:

t=# select unnest(string_to_array(t,'-')) from so65;
     unnest
-----------------
 Curaçao
 Amsterdam
 St. Christopher
 Essequibo
 Texel
 Riohacha
 Buenos Aires
 La Rochelle
(8 rows)

Time: 1.662 ms

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM