计数 MySQL 中的非空值的出现


要计算非空值的数量,请使用总体函数 COUNT(yourColumnName)。我们首先创建一个表 −

mysql> create table DemoTable
   (
   Id int NOT NULL AUTO_INCREMENT PRIMARY KEY,
   NumberOfQuestion int,
   NumberOfSolution int
   );
Query OK, 0 rows affected (0.20 sec)

使用插入命令在表中插入一些记录。此处,其中一些值为空 −

mysql> insert into DemoTable(NumberOfQuestion,NumberOfSolution) values(20,10);
Query OK, 1 row affected (0.06 sec)

mysql> insert into DemoTable(NumberOfQuestion,NumberOfSolution) values(20,2);
Query OK, 1 row affected (0.04 sec)

mysql> insert into DemoTable(NumberOfQuestion,NumberOfSolution) values(20,NULL);
Query OK, 1 row affected (0.03 sec)

mysql> insert into DemoTable(NumberOfQuestion,NumberOfSolution) values(20,NULL);
Query OK, 1 row affected (0.05 sec)

mysql> insert into DemoTable(NumberOfQuestion,NumberOfSolution) values(30,19);
Query OK, 1 row affected (0.04 sec)

mysql> insert into DemoTable(NumberOfQuestion,NumberOfSolution) values(30,1);
Query OK, 1 row affected (0.04 sec)

使用选择语句从表中显示所有记录 −

mysql> select *from DemoTable;

这会产生以下输出 −

+----+------------------+------------------+
| Id | NumberOfQuestion | NumberOfSolution |
+----+------------------+------------------+
| 1  | 20               | 10               |
| 2  | 20               | 2                |
| 3  | 20               | NULL             |
| 4  | 20               | NULL             |
| 5  | 30               | 19               |
| 6  | 30               | 1                |
+----+------------------+------------------+
6 rows in set (0.00 sec)

以下是计算值数量的查询。相同的值不应为非空,即不统计空值−

mysql> SELECT NumberOfQuestion, COUNT(NumberOfSolution) as NumberOfRows FROM DemoTable GROUP BY NumberOfQuestion;

这会产生以下输出 −

+------------------+--------------+
| NumberOfQuestion | NumberOfRows |
+------------------+--------------+
| 20               | 2            |
| 30               | 2            |
+------------------+--------------+
2 rows in set (0.00 sec)

更新于: 2019-7-30

599 次浏览

开启你的 职业生涯

完成课程获得认证

立即开始
广告