【问题标题】:How can I use and IF statement within a REPLACE () statement?如何在 REPLACE () 语句中使用和 IF 语句?
【发布时间】:2017-08-30 20:07:38
【问题描述】:

收到关于在 REPLACE 语句中使用 IF 语句的查询(如果可能的话!)

例子:

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

这样行得通,但我需要一个 IF 语句来根据他们的性别区分他们是鳏夫还是寡妇(可以从另一列中提取)。

我会在开始 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')

不确定我是否嵌套了这个错误,但我似乎无法让它工作,有什么想法吗?

【问题讨论】:

    标签: sql oracle if-statement replace reporting


    【解决方案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
    

    【讨论】:

    • 我确定这是否是 Oracle 的语法 - 但试一试
    • 它很接近,但我已经对其进行了调整,因此它实际上可以在 Oracle 中运行... *8-)
    • 感谢特伦特,这很有帮助!
    【解决方案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                                            
    

    【讨论】:

    • 我投了赞成票,因为我喜欢这个答案。我最初想到了 REPLACE 之外的 CASE,但我喜欢在内部使用它的这个版本。此外,示例和验证数据做得很好。
    猜你喜欢
    • 2021-01-25
    • 2020-12-02
    • 1970-01-01
    • 1970-01-01
    • 2015-01-26
    • 1970-01-01
    • 2020-06-23
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多