您可以COUNT()
为此使用功能。让我们首先创建一个演示表
mysql> create table countValueDemo -> ( -> ShippingDatetime datetime, -> FirstValue int, -> SecondValue int -> );
使用insert命令在表中插入一些记录。查询如下-
mysql> insert into countValueDemo values('2019-01-23',1,2); mysql> insert into countValueDemo values('2017-02-21',NULL,2); mysql> insert into countValueDemo values('2016-04-12',1,NULL);
使用select语句显示表中的所有记录。查询如下-
mysql> select *from countValueDemo;
以下是输出
+---------------------+------------+-------------+ | ShippingDatetime | FirstValue | SecondValue | +---------------------+------------+-------------+ | 2019-01-23 00:00:00 | 1 | 2 | | 2017-02-21 00:00:00 | NULL | 2 | | 2016-04-12 00:00:00 | 1 | NULL | +---------------------+------------+-------------+ 3 rows in set (0.00 sec)
这是选择按值计数的查询
mysql> SELECT ShippingDatetime, -> COUNT(*), -> COUNT( IF( FirstValue = 1, 1, NULL ) ), -> COUNT( IF( SecondValue = 2, 1, NULL ) ) -> FROM countValueDemo;
以下是输出
+---------------------+----------+----------------------------------------+-----------------------------------------+ | ShippingDatetime | COUNT(*) | COUNT( IF( FirstValue = 1, 1, NULL ) ) | COUNT( IF( SecondValue = 2, 1, NULL ) ) | +---------------------+----------+----------------------------------------+-----------------------------------------+ | 2019-01-23 00:00:00 | 3 | 2 | 2 | +---------------------+----------+----------------------------------------+-----------------------------------------+ 1 row in set (0.08 sec)