mysql求和null,MySQL-仅在所有行都不为null时求和,否则返回null

Let's suppose the following table:

X VALUE

1 2

1 3

2 NULL

2 4

I want a result set grouped by X with the sum of VALUE, but only if all the rows related to each X value are not null.

Using the same example, the result must be:

X SUM(VALUE)

1 5

As you can see, X=2 is not selected due to the (2, NULL) tuple.

I want, whenever this is possible, without using subqueries.

Thank you very much!

解决方案

You can achieve that with:

SELECT

x,

SUM(value)

FROM

t

GROUP BY

x

HAVING

COUNT(value)=COUNT(*)

This will work following way: group values in normal way, but then compare entire count (so * points to that) with column count (which won't include NULL-s). If they are not equal, then there are NULL's and value shouldn't be included.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值