问题
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