如何在REPLACE()语句中使用IF语句?

时间:2017-04-05 09:35:07

标签: sql oracle if-statement replace reporting

有一个关于在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')

我不确定自己是否错了,但我似乎无法让这个工作,任何想法?

2 个答案:

答案 0 :(得分:2)

您可以使用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                                            

答案 1 :(得分: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