2

I have a small Porstgre database where I a have a table with several columns. One of those columns contains data like this : test1 (80%) test2 (21%) test3 (40%) etc ...

What I would like to do, is to be able to move that percentage to another column so the data will look like :

TEST_COLUMN | PERCENTAGE_COLUMN

test1       | 80%

test2       | 21%

etc...

Knowing that I have over 10k records, it would be helpful if there is a way to achieve this without having to move anything manually. Thank in advance

2 Answers 2

3

You could use REGEXP:

SELECT  col ,TRIM(REGEXP_REPLACE(col, '(\(\d+%\))$', '')) AS test_column
       ,(REGEXP_MATCHES(col, '(\d+%)\)$'))[1] AS percentage_column
FROM t;

DBFiddle Demo

Sign up to request clarification or add additional context in comments.

1 Comment

I do like this answer as it's easier than the first one, and it worked well. Thank sir
2

you can just regexp it, or other text process, eg:

t=# with a(v) as (values('test1 (80%)'),('test2 (21%)'),('test3 (40%)'))
, p as (select v,string_to_array(v,'(') ar from a)
select v, ar[1],translate(ar[2],')','') from p;
      v      |   ar   | translate
-------------+--------+-----------
 test1 (80%) | test1  | 80%
 test2 (21%) | test2  | 21%
 test3 (40%) | test3  | 40%
(3 rows)

1 Comment

I didn't know we could do such thing and use regex in sql. Thank for your answer but looks a bit complicated tho.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.