【问题标题】:Why is my case statement not returning the value in my "else" clause?为什么我的 case 语句没有返回“else”子句中的值?
【发布时间】:2020-09-29 20:40:32
【问题描述】:

我有这部分代码,但我的 ELSE 不工作。它应该返回 'UNKNOWN' 但我仍然在我的结果中看到 NULL。怎么回事?

      case 
            when t2.NEURO_GRP_2 is not NULL then t2.NEURO_GRP_1 --ASSIGN GROUP 2 BASED ON PRIMARY DX CODE
            when t2.NEURO_GRP_2 is null AND t6.NEURO_GRP_2 IS NOT NULL then t6.NEURO_GRP_2 --ASSIGN GROUP 2 BASED ON CLINIC
            when t2.NEURO_GRP_2 is null AND t6.NEURO_GRP_2 IS NULL then t3.NEURO_GRP_3 --ASSIGN GROUP 2 BASED ON PROCEDURE GROUP
            ELSE 'UNKNOWN' 
            end AS NEURO_GRP_2,

【问题讨论】:

  • 也许when t2.NEURO_GRP_2 is not NULL then t2.NEURO_GRP_1 应该是when t2.NEURO_GRP_2 is not NULL then t2.NEURO_GRP_2

标签: sql string case sql-null


【解决方案1】:

也许你想要coalesce():

coalesce(t2.NEURO_GRP_2, t6.NEURO_GRP_2, t3.NEURO_GRP_3, 'UNKNOWN')

这将返回第一个非NULL 值。由于最后一个参数是常数,它永远不会返回NULL

【讨论】:

    【解决方案2】:

    看起来coalesce() 确实如你所愿:

    coalesce(t2.NEURO_GRP_2, t6.NEURO_GRP_2, t3.NEURO_GRP_3, 'UNKNOWN') S NEURO_GRP_2
    

    您的原始代码的问题可能是:

    • 第一个条件不匹配(检查一列是否为空,但返回另一列)

    • 条件在某种程度上是多余的,并且没有正确级联

    你的意思可能是:

    case 
        when t2.NEURO_GRP_2 IS NOT NULL then t2.NEURO_GRP_2
        when t6.NEURO_GRP_2 IS NOT NULL then t6.NEURO_GRP_2
        when t3.NEURO_GRP_3 IS NOT NULL then t3.NEURO_GRP_3
        else 'UNKNOWN' 
    end AS NEURO_GRP_2
    

    ...这正是coalesce() 所做的。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多