【问题标题】:mysql show 0 if selected value is null?如果选择的值为空,mysql显示0?
【发布时间】:2012-01-24 09:02:25
【问题描述】:

我有一个很长的 sql 查询,用于计算一些关于付款和发货的事情。在某些情况下,该值为null. 我认为这是因为它被除以0。

这是我查询的一小部分:

     ROUND(sum(case when shipping_method = 'c' AND (paid_amount - shipping_costs) < 70 then 1 end) * 100 / sum(case when shipping_method = 'c' then 1 end),2) as co_less_70,

我认为当这部分为 0 时:sum(case when shipping_method = 'colissimo' then 1 end),2) 我的查询显示为空。有没有办法为这个co_less_70 列分配一个默认值?

【问题讨论】:

    标签: mysql null default-value


    【解决方案1】:

    是的。你可以使用COALESCE()函数:

    http://dev.mysql.com/doc/refman/5.0/en/comparison-operators.html#function_coalesce
    返回列表中的第一个非 NULL 值,如果没有非 NULL 值,则返回 NULL。

    在您的代码中:

    COALESCE(
        ROUND(sum(case when shipping_method = 'c' AND (paid_amount - shipping_costs) < 70 then 1 end) * 100 / sum(case when shipping_method = 'c' then 1 end),2),
        0
    ) AS co_less_70
    

    【讨论】:

      【解决方案2】:

      您可以设置默认大小写,但除零之外的任何内容:-

      sum(case when shipping_method = 'colissimo' then 1 else some_value end case),2)
      

      【讨论】:

      • 用户想要为整列分配一个默认值,当它是NULL时,而不只是当除数是0时的默认值。
      • 如果没有 shipping_method = 'c' 的行,那么您将得到 0 / 0 ,这可能是导致问题的原因。这不会解决它 - 任何其他值都会抛出数学问题。
      【解决方案3】:
      IFNULL(
        ROUND(sum(case when shipping_method = 'c' AND (paid_amount - shipping_costs) < 70 then 1 end) * 100 / sum(case when shipping_method = 'c' then 1 end),2)
      ,<default>) AS co_less_70,
      

      【讨论】:

        猜你喜欢
        • 2020-06-14
        • 1970-01-01
        • 1970-01-01
        • 2021-03-03
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多