mysql sum 没返回,如果没有找到任何值,我如何在MySQL中获得SUM函数以返回'0'?

Say I have a simple function in MySQL:

SELECT SUM(Column 1) from Table WHERE Column 2='Test'

If no entries in Column 2 contain the text 'Test' then this function returns NULL, while I would like it to return 0.

I'm aware that a similar question has been asked a few times here, but I haven't been able to adapt the answers to my purposes, so I'd be grateful for some help to get this sorted.

解决方案

Use COALESCE to avoid that outcome.

SELECT COALESCE(SUM(column),0)

FROM table

WHERE ...

To see it in action, please see this sql fiddle: http://www.sqlfiddle.com/#!2/d1542/3/0

More Information:

Given three tables (one with all numbers, one with all nulls, and one with a mixture):

MySQL 5.5.32 Schema Setup:

CREATE TABLE foo

(

id INT NOT NULL AUTO_INCREMENT PRIMARY KEY,

val INT

);

INSERT INTO foo (val) VALUES

(null),(1),(null),(2),(null),(3),(null),(4),(null),(5),(null),(6),(null);

CREATE TABLE bar

(

id INT NOT NULL AUTO_INCREMENT PRIMARY KEY,

val INT

);

INSERT INTO bar (val) VALUES

(1),(2),(3),(4),(5),(6);

CREATE TABLE baz

(

id INT NOT NULL AUTO_INCREMENT PRIMARY KEY,

val INT

);

INSERT INTO baz (val) VALUES

(null),(null),(null),(null),(null),(null);

Query 1:

SELECT 'foo' as table_name,

'mixed null/non-null' as description,

21 as expected_sum,

COALESCE(SUM(val), 0) as actual_sum

FROM foo

UNION ALL

SELECT 'bar' as table_name,

'all non-null' as description,

21 as expected_sum,

COALESCE(SUM(val), 0) as actual_sum

FROM bar

UNION ALL

SELECT 'baz' as table_name,

'all null' as description,

0 as expected_sum,

COALESCE(SUM(val), 0) as actual_sum

FROM baz

| TABLE_NAME | DESCRIPTION | EXPECTED_SUM | ACTUAL_SUM |

|------------|---------------------|--------------|------------|

| foo | mixed null/non-null | 21 | 21 |

| bar | all non-null | 21 | 21 |

| baz | all null | 0 | 0 |

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值