2017-04-05 173 views
0

有一个查询中关于使用REPLACE语句中的IF语句如何在REPLACE()语句中使用IF语句?

实例(如果可能的话!):

REPLACE("Person Legislative Information"."Marital Status",'Widowed','Widower') 

这样的作品,但我需要有一个IF语句来区分根据他们的性别(可以从另一列中拉出)来判断他们是W夫还是寡妇。

我会在启动REPLACE语句之前放置一条IF语句吗?

例子:

REPLACE(REPLACE(IF("Worker"."Gender" = 'M')"Person Legislative Information"."Marital Status",'Widowed','Widower')IF("Worker"."Gender" = 'F')"Person Legislative Information"."Marital Status",'Widowed','Widow') 

不知道如果我筑巢这个错误的,但我似乎无法得到这个工作,任何想法?

回答

1

可以使用case expression来决定使用哪个替换值:

REPLACE("Person Legislative Information"."Marital Status", 
    'Widowed', CASE "Worker"."Gender" WHEN 'F' THEN 'Widow' ELSE 'Widower' END) 

演示:

with "Worker" (id, "Gender") as (
    select 1, 'M' from dual 
    union all select 2, 'F' from dual 
), 
"Person Legislative Information" (id, "Marital Status") as (
    select 1, 'Widowed' from dual 
    union all select 2, 'Widowed' from dual 
) 
SELECT "Worker"."Gender", "Person Legislative Information"."Marital Status", 
    REPLACE("Person Legislative Information"."Marital Status", 
    'Widowed', CASE "Worker"."Gender" WHEN 'F' THEN 'Widow' ELSE 'Widower' END) 
    AS "New Marital Status" 
FROM "Worker" 
JOIN "Person Legislative Information" 
ON "Person Legislative Information".id = "Worker".id; 

G Marital New Marital Status        
- ------- ------------------------------------------------- 
M Widowed Widower           
F Widowed Widow            
+0

完美的谢谢Alex! –

+0

我高兴,因为我喜欢这个答案。我最初想到了REPLACE之外的CASE,但我喜欢这个版本在里面使用它。此外,示例和验证数据也做得很好。 – unleashed

1

我认为你正在寻找一个CASE语句

SELECT 
    CASE "Worker"."Gender" 
    WHEN 'F' THEN 
     REPLACE("Person Legislative Information"."Marital Status", 'Widowed', 'Widow') 
    ELSE 
     REPLACE("Person Legislative Information"."Marital Status", 'Widowed', 'Widower') 
    END marital_status 
+0

我肯定确定这是否是Oracle的语法 - 但给它一个 – Trent

+0

这是正确的语法 – Sebas

+0

它很接近,但我调整了它,所以它实际上在Oracle中工作... * 8-) –