1

当任一字段为NULL时,我希望返回的值NULL也是如此。我也尝试过颠倒逻辑:is not null. 还是一样的结果。

mysql代码:

(case
            when
                ((`creative_stg_sample_tracking_raw`.`total_samples_received` is not null)
                    and (`creative_stg_sample_tracking_raw`.`total_samples_forecasted` is not null))
            then
                (cast(`creative_stg_sample_tracking_raw`.`total_samples_received`
                    as signed) - cast(`creative_stg_sample_tracking_raw`.`total_samples_forecasted`
                    as signed))
            else NULL
        end) AS `received_forecasted_dif`

截屏:

截屏

4

1 回答 1

1

您的代码应该可以工作,但您不需要case. 每当其中一个值是NULL时,表达式应该是NULL

(cast(`creative_stg_sample_tracking_raw`.`total_samples_received` as signed) -
 cast(`creative_stg_sample_tracking_raw`.`total_samples_forecasted` as signed))
) AS `received_forecasted_dif`

我想知道您的问题是否是该值实际上是'NULL'而不是NULL. 也就是说,一个字符串值而不是一个真正的 NULL。MySQL 会将字符串视为0算术运算。

您可以通过以下方式解决此问题:

(case when `creative_stg_sample_tracking_raw`.`total_samples_received` <> 'NULL' and
           `creative_stg_sample_tracking_raw`.`total_samples_forecasted` <> 'NULL'
      then (cast(`creative_stg_sample_tracking_raw`.`total_samples_received` as signed) -
            cast(`creative_stg_sample_tracking_raw`.`total_samples_forecasted` as signed))
           )
      else NULL
end) AS `received_forecasted_dif`
于 2013-08-23T14:46:26.037 回答