I have a table with employee data inside:
+----+-------+----------+------------+
| ID | Name | LastName | Salutation |
+----+-------+----------+------------+
| 1 | John | Doe | Mr |
| 2 | Alice | Smith | Ms |
+----+-------+----------+------------+
I want to select some of that data but I want to replace Mr
with 1
and Ms
with 2
using the SQL query itself.
I have tried to use REGEXP_REPLACE
what actually did work for one of the salutations:
SELECT ID, Name, LastName, REGEXP_REPLACE(Salutation, 'Mr', '1') FROM employees
It gave me a following result:
+----+-------+----------+------------+
| ID | Name | LastName | Salutation |
+----+-------+----------+------------+
| 1 | John | Doe | 1 |
| 2 | Alice | Smith | Ms |
| 3 | John | Smith | 1 |
| 4 | Alice | Doe | Ms |
+----+-------+----------+------------+
How can I replace also Ms
to 2
?
You can use the decode
select ID, Name, LastName.
DECODE(Salutation,'Mr',1,2) as Salutation
from employee
You can achieve it by using case
statement. Here is the DEMO
select
ID,
Name,
LastName,
(case when Salutation = 'Mr' then 1 else 2 end) as Salutation
from employee
order by
ID
SELECT
ID, Name, LastName,
REPLACE(TMP_TABLE.TMP_Salutation, 'Ms', '2')
FROM (
SELECT
REPLACE(Salutation, 'Mr', '1') TMP_Salutation
FROM employees
) TMP_TABLE;
This code will first replace all occurances of 'Mr' with '1' in the subquery and return a table which we gave an alias of 'TMP_TABLE'. Then, all the occurances of 'Ms' in that 'TMP_TABLE' will be replaced with '2'
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.