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 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: