SQL query to return NULL for SUM(expression) whenever an included value IS NULL
For MySQL, I want a query that returns a SUM of an expression, EXCEPT that I want the returned value to be NULL if any of the expressions included in the SUM are NULL. (The normal operation of SUM is to ignore NULL values.
Here's a simple test case that illustrates
CREATE TABLE t4 (fee VARCHAR(3), fi INT);
INSERT INTO t4 VALUES ('fo',10),('fo',200),('fo',NULL),('fum',400);
SELECT fee, SUM(fi) AS sum_fi FROM t4 GROUP BY fee
This returns exactly the result set I开发者_JAVA技巧 expect:
fee sum_fi
--- ------
fo 210
fum 400
What I want is a query that returns a DIFFERENT result set:
fee sum_fi
--- ------
fo NULL
fum 400
What I want is for the value returned for sum_fi to be NULL whenever an included value is NULL. (This is different than the SUM aggregate function ignores NULL, and returns a total for the non-NULL expressions.)
Question: What query can I use to return the desired result set?
I don't find any built in aggregate function that exhibits this behavior.
How about using SUM(fi is NULL)
to determine if you have a NULL value in your data set?
This should work:
SELECT fee, IF(SUM(fi is NULL), NULL, SUM(fi)) AS sum_fi FROM t4 GROUP BY fee
You can use this query:
SELECT fee,
IF(COUNT(fi) < (SELECT count(fee) FROM t4 temp2 WHERE temp1.fee = temp2.fee),
NULL, SUM(fi)) AS sum_fi
FROM t4 temp1 GROUP BY fee
There is also this solution:
SELECT fee, CASE WHEN COUNT(*) = COUNT(fi) THEN SUM(fi) ELSE NULL END AS sum_fi
FROM t4 GROUP BY fee
which I derived from the answer of the question Aaron W tagged as a duplicate of this. Admittedly, the latter form looks better than my original idea.
精彩评论