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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.