依据值选择 MySQL 数值?


你可以使用 COUNT() 函数执行此操作。我们首先创建一个演示表

mysql> create table countValueDemo
   -> (
   -> ShippingDatetime datetime,
   -> FirstValue int,
   -> SecondValue int
   -> );
Query OK, 0 rows affected (1.35 sec)

使用插入命令在表中插入一些记录。查询如下所示 −

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)

更新于: 30-Jul-2019

98 浏览次数

开启你的 职业生涯

完成课程,获得认证

立即开始
广告