0

I have three columns:

Name           | Number  | Number2
abc $18 12mb   | $18     | 12mb
10mb 1cd $19   | $19     | 10mb
$15 30mb ab123 | $15     | 30mb

I want to create column: new_name as name without number and number2. Any ideas?

Expected output:

Name      | Number  | Number2
abc       | $18     | 12mb
1cd       | $19     | 10mb
ab123     | $15     | 30mb

2 Answers 2

2

One method uses replace():

select trim(both ' ' from replace(name, Number, ''))
Sign up to request clarification or add additional context in comments.

Comments

1

Just nest your replace statements. Simple way:

alter table mytable add new_name text;

update mytable set new_name =     
trim(both ' ' from replace(replace("name", "Number", ''),"Number2", ''))

Note that this won't work for cases where either column is null. Hanlde nulls with coalesce():

update mytable set new_name =     
    trim(both ' ' from replace(replace("name", coalesce("Number",''), ''),coalesce("Number2",''), ''))

This will still fail if Number is a substring of Number2, because the inner replace will replace that bit of the Number2 part and the outer replace won't do anything. You can do a more complicated way that should work in all cases:

-- replace the longer string first
 update mytable set new_name =     
 CASE WHEN coalesece(length("Number"),0) > coalesce(length("Number2"),0) THEN 
    trim(both ' ' from replace(replace("name", coalesce("Number",''), ''),coalesce("Number2",''), ''))
 ELSE
    trim(both ' ' from replace(replace("name", coalesce("Number2",''), ''),coalesce("Number",''), ''))
END

For the case where the numbers are the same length (and identical) this will work, because the inner replace will do what you want.

1 Comment

Ok thanks! what if for one Name Number is only filled (without number2)? If trim(both ' ' from replace(replace(name, "Number", ''),"Number2", '')) it returns blank.

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.