如果所有行都不为空,则求和,否则在 MySQL 中返回 null?
你可以借助 GROUP BY HAVING 子句实现此目的。语法如下 -
SELECT yourColumnName1, SUM(yourCoumnName2) from yourTableName GROUP BY yourColumnName1 HAVING COUNT(yourCoumnName2) = COUNT(*);
为了理解以上语法,我们创建一个表。创建表的查询如下 -
mysql> create table SumDemo -> ( -> Id int, -> Amount int -> ); Query OK, 0 rows affected (0.58 sec)
使用 insert 命令在表中插入一些记录。查询如下 -
mysql> insert into SumDemo values(1,200); Query OK, 1 row affected (0.22 sec) mysql> insert into SumDemo values(2,100); Query OK, 1 row affected (0.19 sec) mysql> insert into SumDemo values(2,NULL); Query OK, 1 row affected (0.14 sec) mysql> insert into SumDemo values(1,300); Query OK, 1 row affected (0.16 sec) mysql> insert into SumDemo values(2,100); Query OK, 1 row affected (0.17 sec) mysql> insert into SumDemo values(1,500); Query OK, 1 row affected (0.16 sec)
使用 select 语句显示表中的所有记录。查询如下 -
mysql> select *from SumDemo;
输出
+------+--------+ | Id | Amount | +------+--------+ | 1 | 200 | | 2 | 100 | | 2 | NULL | | 1 | 300 | | 2 | 100 | | 1 | 500 | +------+--------+ 6 rows in set (0.00 sec)
以下是,如果所有行都不为空,则求和,否则返回 null 的查询。查询如下 -
mysql> select Id, -> SUM(Amount) -> from SumDemo -> GROUP BY ID -> HAVING COUNT(Amount) = COUNT(*);
以下是输出。由于 id 2 为 NULL,因此它的任何值都不会添加到和中。
因此,将添加 Id 1 的所有值,即 200 + 300 + 500 = 1000,如下所示 -
+------+-------------+ | Id | SUM(Amount) | +------+-------------+ | 1 | 1000 | +------+-------------+ 1 row in set (0.09 sec)
广告