2017-04-21 40 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。 –