[英]Function to extract array items to different columns postgresql
I'm trying to design a function to solve this problem. 我正在尝试设计一个函数来解决此问题。 I have column with cities that looks like this. 我有一些类似这样的城市专栏。
1 |Curaçao-Amsterdam
2 |St. Christopher-Essequibo
3 |Texel-Riohacha-Buenos Aires-La Rochelle`
And I have used this query to extract it to an array of elements 我已经使用此查询将其提取到元素数组中
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
That gives this result: 得出以下结果:
{Curaçao,Amsterdam} {"St. Christopher",Essequibo} {Texel,Riohacha,"Buenos Aires","La Rochelle"}`
And I want to create a function to extract * array elements to different columns. 我想创建一个函数来提取*数组元素到不同的列。 I have thought of a while function like this: 我想到了这样的一会儿功能:
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;
But I'm not sure it is a proper solution, and how to implement it. 但我不确定这是否是正确的解决方案以及如何实施。 Any hint? 有什么提示吗? Thanks in advance! 提前致谢!
is it what you try to do? 这是您尝试做的吗?
create table: 创建表:
t=# create table so65 (i int, t text);
CREATE TABLE
Time: 55.234 ms
populate data: 填充数据:
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
split: 分裂:
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
to one column: 到一栏:
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.