无法使用 CAST() 添加 DOUBLE 和 VARCHAR 列

Unable to add DOUBLE and VARCHAR columns with CAST()

我的 billing table:

中有两列

当我:

SELECT CONCAT_WS("", "$", FORMAT(db.billing.cost_per_month, 2)) AS "Monthly Cost",
  CONCAT_WS("", "$", FORMAT(db.billing.additional_cost, 2)) AS "Additional Cost",
  CONCAT_WS("", "$", FORMAT(CAST(db.billing.cost_per_month AS DECIMAL(60, 2)) + db.billing.additional_cost, 2)) AS "Total Cost"
  FROM db.billing;

我得到:

Monthly Cost  Additional Cost  Total Cost
,000.00     $                $
[=11=].00         0.00          0.00
0.00       0.00          $

而不是:

Monthly Cost  Additional Cost  Total Cost
,000.00     [=12=].00            ,000.00
[=12=].00         0.00          0.00
0.00       0.00          0.00

我试过:

问题是由于当没有 cost_per_monthadditional_cost 行时存在 NULL 值。

解决方法是使用 COALESCE() 而不是 CAST()

你的情况:

SELECT CONCAT_WS("", "$", FORMAT(COALESCE(db.billing.cost_per_month, 0.00), 2)) AS "Monthly Cost",
  CONCAT_WS("", "$", FORMAT(COALESCE(db.billing.additional_cost, 0.00),  2)) AS "Additional Cost",
  CONCAT_WS("", "$", FORMAT(COALESCE(db.billing.cost_per_month, 0.00) AS DECIMAL(60, 2)) + COALESCE(db.billing.additional_cost, 0.00), 2)) AS "Total Cost"
  FROM db.billing;