SUM函数,如果存在空值则返回空

时间:2018-08-07 22:29:52

标签: mysql sql

我有这个查询

SELECT (SELECT cost FROM table1 t2 WHERE t2.edate=>table1.edate) AS cost
FROM table1
WHERE table1.orderNo = 'CS119484568'

以上查询返回:

cost
4
3
null
null
5

我想获取全部的总和,或者如果任何行为空,则为空

SELECT SUM((SELECT cost FROM table1 t2 WHERE t2.edate=>table1.edate)) AS cost
FROM table1
WHERE table1.orderNo = 'CS119484568'

在上述情况下,预期结果为NULL。

3 个答案:

答案 0 :(得分:0)

这是我的尝试:

SELECT
    (SELECT
        case when count(*)=count(cost) then sum(cost) else null end
     FROM table1 t2
     WHERE t2.edate=>table1.edate
    ) AS cost
FROM table1
WHERE table1.orderNo = 'CS119484568'

这是基于count()仅计算非空值的事实。

答案 1 :(得分:0)

您可以使用if

SELECT IF((SELECT COUNT(*) FROM table1 t2 WHERE t2.edate=>table1.edate AND cost IS NULL), null, (SELECT SUM(cost) FROM table1 t2 WHERE t2.edate=>table1.edate)) AS cost FROM table1 WHERE table1.orderNo = 'CS119484568'

答案 2 :(得分:0)

我想我的查询短语为:

SELECT SUM(CASE WHEN t1.edate >= tt1.edate THEN cost END)
FROM table1 t1 CROSS JOIN
     (SELECT edate
      FROM table1
      WHERE t1.orderNo = 'CS119484568'
     ) tt1;

然后我将使用CASE表达式作为结果:

SELECT (CASE WHEN SUM(t1.edate >= tt1.edate AND cost IS NOT NULL) = 0  -- no nulls
             THEN SUM(CASE WHEN t1.edate >= tt1.edate THEN cost END)
        END)
FROM table1 t1 CROSS JOIN
     (SELECT edate
      FROM table1
      WHERE t1.orderNo = 'CS119484568'
     ) tt1;