Search code examples
postgresqlsplitpostgresql-9.5

SPLIT_PART with a negative value [Postgres 9.5]


I need to use the split_part function on that query:

CREATE TABLE client_group_by_group_test AS SELECT *, SPLIT_PART( groupe,
 ',', 1 ) AS group1, SPLIT_PART(SPLIT_PART(groupe,',',2),',',-1) AS 
 group2, SPLIT_PART(SPLIT_PART(groupe,'',3),'',-3) AS group3, 
 SPLIT_PART(groupe,'',-4) AS group4 FROM planification_client

but it gives me the following error:

ERROR: field position must be greater than zero

So, how can I deal with negative values here?

Can this kind reverse(split_part(reverse(col_A), '_'::text, 1)) of statement work? I'm referencing to that question.

EDIT: I'm completely stuck with this query.

More details: I have one column with "server name" and another with its different groups separated with coma.

server name| group                        |
-----------+------------------------------+
XPTERTBIEP9|GRNW_SPO_S_F_H, GRNW_SPO_S_I_J|

The output I need to get is if the server has multiple groups, they need to be in the different column like group1, group2...

server name| group                        |group1        |group 2
-----------+------------------------------+--------------+--------------
XPTERTBIEP9|GRNW_SPO_S_F_H, GRNW_SPO_S_I_J|GRNW_SPO_S_F_H|GRNW_SPO_S_I_J

Solution

  • If the negative number is supposed to indicated the offset from the end, a two step approach might be better:

    CREATE TABLE client_group_by_group_test 
    AS 
    SELECT ..., 
           agroups[1] as group1,
           agroups2[cardinality(agroups2) - 1] as groups2,
           agroups3[cardinality(agroups3) - 3] as groups3,
           agroups[cardinality(agroups) - 4] as group4
    from (
       select *,
              string_to_array(groupe, ',') as agroups, 
              (string_to_array(string_to_array(groupe, ','), ',')[2]) as agroups2,
              (string_to_array(string_to_array(groupe, ','), ',')[3]) as agroups3,
       from planification_client
    ) t
    

    Note that you need to list the desired columns in the outer most SELECT to exclude the intermediate "agroups" columns.