简体   繁体   中英

How to remove part of string in a column based on content of another column in Oracle

I have database tables that look like this:

Class   | ClassNumber
S       | S3
T       | T37
T       | T50
S       | SS07
S       | S4
S       | SG27

ClassNumber contains the value of Class and another identifier. So meaning that if the Class is S , then it means ClassNumber must begin with S and followed by another identifier.

I would like to extract the identifier in ClassNumber .

If I use the REPLACE function, it will replace all characters that match. But I only want the prefix to be removed.

SELECT REPLACE(ClassNumber, Class, '') FROM MY_TABLE

This will make SS07 to be 07 instead. But I want it to return S07 .

How do I do this?

Try REGEXP_REPLACE

SELECT CLASSNUMBER,REGEXP_REPLACE(ClassNumber, '^'||Class, '') as id FROM t

Or if you are sure that it's always a single digit class, simply use

SUBSTR(CLASSNUMBER,2)

Demo

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM