【问题标题】:Function to extract array items to different columns postgresql将数组项提取到不同列postgresql的函数
【发布时间】:2017-09-18 04:19:57
【问题描述】:

我正在尝试设计一个函数来解决这个问题。我的专栏中的城市看起来像这样。

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"}`

我想创建一个函数来将 * 数组元素提取到不同的列。我想到了这样的while函数:

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;

但我不确定这是一个正确的解决方案,以及如何实施它。有什么提示吗? 提前致谢!

【问题讨论】:

  • "将*数组元素提取到不同的列"?..你的意思是动态列数吗?..
  • 为什么不string_to_array(rutacompleta,'-')?..

标签: arrays postgresql function


【解决方案1】:

这是你尝试做的吗?

创建表:

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

【讨论】:

  • 感谢您的反馈。是的,最终我认为最好执行此解决方案并保留每个城市子集的 id。
猜你喜欢
  • 2021-12-21
  • 2023-03-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-07-01
  • 1970-01-01
  • 2013-05-29
  • 2021-10-06
相关资源
最近更新 更多