无法使用 CAST() 添加 DOUBLE 和 VARCHAR 列
Unable to add DOUBLE and VARCHAR columns with CAST()
我的 billing
table:
中有两列
cost_per_month
、VARCHAR
additional_cost
、DOUBLE
当我:
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
我试过:
- 使用
CAST(db.billing.cost_per_month AS SIGNED)
- 使用
CAST(db.billing.cost_per_month AS UNSIGNED)
- 删除
FORMAT()
和 CONCAT_WS()
函数
- 使用
SUM()
多种不同的方式
问题是由于当没有 cost_per_month
或 additional_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;
我的 billing
table:
cost_per_month
、VARCHAR
additional_cost
、DOUBLE
当我:
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
我试过:
- 使用
CAST(db.billing.cost_per_month AS SIGNED)
- 使用
CAST(db.billing.cost_per_month AS UNSIGNED)
- 删除
FORMAT()
和CONCAT_WS()
函数 - 使用
SUM()
多种不同的方式
问题是由于当没有 cost_per_month
或 additional_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;