2017-04-21 42 views
0

我試圖設計一個函數來解決這個問題。我有與這樣的城市專欄。將數組項目提取到不同列的函數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; 

但我不確定這是一個合適的解決方案,以及如何實現它。任何提示? 在此先感謝!

+0

「額外ct *數組元素到不同的列「?..你的意思是一些動態數列嗎? –

+0

爲什麼不'string_to_array(rutacompleta,' - ')'?.. –

回答

0

是你想要做的嗎?

創建表:

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 
+0

感謝您的反饋。是的,最終我認爲做這個解決方案會更好,並保留每個城市子集的ID。 –