Invalid Length: field position must be greater than zero

不羁岁月 提交于 2019-12-11 14:49:35

问题


I am trying to transform a column in PostgresSQL:

Here are some values in col_A:

col_A
---------
John_arrived
Mary_Brown_arrived
J_C_Jr_arrived
Q_arrived

The aim is to get the first part and last part of col_A only:

d_col_A
-------
John_arrived
Mary_arrived
J_arrived
Q_arrived

Here is my query:

with t1 as (
select split_part(col_A, '_'::text, 1) || '_' 
    || COALESCE (split_part(col_A, '_'::text, -1), '' ) as d_col_A
    from my_table
)

select distinct d_col_A from t1

Then I got the following errors:

Invalid Length
  Detail: 
  -----------------------------------------------
  error:  Invalid Length
  code:      8001
  context:   field position must be greater than zero
  query:     2382655
  location:  funcs_string.cpp:1565
  process:   query0_27 [pid=11502]
  -----------------------------------------------

Any idea what I did wrong? Thanks!


回答1:


If you want the last part of column, you can't use -1. You need to reverse the column and get the first part and reverse again:

reverse(split_part(reverse(col_A), '_'::text, 1))


来源:https://stackoverflow.com/questions/46819485/invalid-length-field-position-must-be-greater-than-zero

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!