MySQL 按值选择计数?
mysqlmysqli database
您可以使用 COUNT() 函数来实现这一点。让我们首先创建一个演示表
mysql> create table countValueDemo -> ( -> ShippingDatetime datetime, -> FirstValue int, -> SecondValue int -> ); Query OK, 0 rows affected (1.35 sec)
使用 insert 命令在表中插入一些记录。 查询语句如下 −
mysql> insert into countValueDemo values('2019-01-23',1,2); Query OK, 1 row affected (0.24 sec) mysql> insert into countValueDemo values('2017-02-21',NULL,2); Query OK, 1 row affected (0.13 sec) mysql> insert into countValueDemo values('2016-04-12',1,NULL); Query OK, 1 row affected (0.19 sec)
使用 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)