简体   繁体   English

SQL将空值的总和转换为0

[英]SQL Converting sum of null values to 0

I have a query in SQL which sum values and add them as months to a date. 我在SQL中有一个查询,该查询将值求和并将它们添加为日期的月份。

    SELECT
    FROM_UNIXTIME(S.created) as start_date, 
   (FROM_UNIXTIME(S.created) + INTERVAL (C.items_left + C.items_given) MONTH)
    AS end_date,
    FROM table1 S
    LEFT JOIN table2 C ON C.id = S.id;

The problem arises when some of these values to sum are null instead of 0 and I am not able to change the source of data. 当这些总和中的某些值为空而不是0时出现问题,而我无法更改数据源。

(FROM_UNIXTIME(S.created) + INTERVAL (C.items_left + C.items_given) MONTH)
AS end_date,

is generating nulls because (C.items_left + C.items_given) is null. 正在生成null,因为(C.items_left + C.items_given)为null。

So, the question is, how do I execute this sum so the result is 0 instead of null? 因此,问题是,如何执行此总和,使结果为0而不是null?

use coalesce 使用coalesce

SELECT
    FROM_UNIXTIME(S.created) as start_date, 
   ( coalesce(FROM_UNIXTIME(S.created),0) + INTERVAL coalesce((coalesce(C.items_left,0) + coalesce(C.items_given,0)),0) MONTH)
    AS end_date,
    FROM table1 S
    LEFT JOIN table2 C ON C.id = S.id;

使用COALESCE()

(FROM_UNIXTIME(S.created) + INTERVAL (COALESCE(C.items_left, 0) + COALESCE(C.items_given, 0)) MONTH)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM