2017-04-21 6 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 

1列:

は、テーブル作成

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を保持する方が良いと思った。 –

関連する問題