将mysql varchar转换为数字然后添加

时间:2017-02-15 14:30:48

标签: mysql

我有一个内部选择的查询:

(SELECT SUM(marketing_fee) FROM answer WHERE  user_id = m.id AND submit_dt between '2017-02-08 23:59:00' and '2017-02-15 23:59:00') as bookedamount,

问题是marketing_fee是一个字符串,可以为空,任何数字都为“null”(但作为字符串结构)。

有没有办法在我的选择中进行转换并将它们一起添加以获得排除空白和空值的单个总数?

由于

enter image description here

1 个答案:

答案 0 :(得分:0)

请改为尝试:

(SELECT SUM(CASE WHEN marketing_fee is NULL THEN 0 ELSE CONVERT(marketing_fee, INTEGER)) FROM answer WHERE  user_id = m.id AND submit_dt between '2017-02-08 23:59:00' and '2017-02-15 23:59:00') as bookedamount

这是文档;

编辑1:

尝试这个更简单的答案:

SELECT SUM(CASE WHEN marketing_fee is NULL OR marketing_fee = '' THEN 0 ELSE marketing_fee) as bookedamount
FROM answer
WHERE user_id = m.id
AND submit_dt between '2017-02-08 23:59:00' and '2017-02-15 23:59:00';