每当包含的值为 NULL 时,SQL 查询就会为 SUM(表达式) 返回 NULL
对于 MySQL,我想要一个返回表达式 SUM 的查询,除非如果 SUM 中包含的任何表达式为 NULL,则我希望返回值为 NULL。 (SUM 的正常操作是忽略 NULL 值。
这是一个简单的测试用例,说明了
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
这将准确返回我期望的结果集:
fee sum_fi
--- ------
fo 210
fum 400
我想要的是返回不同结果集的查询:
fee sum_fi
--- ------
fo NULL
fum 400
我想要的是返回的值当包含的值为 NULL 时,sum_fi 为 NULL(这与 SUM 聚合函数不同,它会忽略 NULL,并返回非 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 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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
如何使用
SUM(fi is NULL)
来确定数据集中是否有 NULL 值?这应该有效:
How about using
SUM(fi is NULL)
to determine if you have a NULL value in your data set?This should work:
您可以使用以下查询:
还有一个解决方案:
我从标记为与此重复的问题 Aaron W 的答案中得出此解决方案。不可否认,后一种形式看起来比我最初的想法更好。
You can use this query:
There is also this solution:
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.