簡體   English   中英

將數組項提取到不同列的功能PostgreSQL

[英]Function to extract array items to different columns 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;

但我不確定這是否是正確的解決方案以及如何實施。 有什么提示嗎? 提前致謝!

這是您嘗試做的嗎?

創建表:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM