每当包含的值为 NULL 时,SQL 查询就会为 SUM(表达式) 返回 NULL

发布于 2024-10-21 22:35:00 字数 646 浏览 1 评论 0原文

对于 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

绮筵 2024-10-28 22:35:00

如何使用 SUM(fi is NULL) 来确定数据集中是否有 NULL 值?
这应该有效:

SELECT fee, IF(SUM(fi is NULL), NULL, SUM(fi)) AS sum_fi FROM t4 GROUP BY fee

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
戏舞 2024-10-28 22:35:00

您可以使用以下查询:

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

还有一个解决方案:

SELECT fee, CASE WHEN COUNT(*) = COUNT(fi) THEN SUM(fi) ELSE NULL END AS sum_fi
FROM t4 GROUP BY fee

我从标记为与此重复的问题 Aaron W 的答案中得出此解决方案。不可否认,后一种形式看起来比我最初的想法更好。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文