如何在单个MySQL查询中计算布尔字段值?
要在单个查询中计算布尔字段值,可以使用CASE语句。让我们创建一个演示表以进行示例 −
mysql> create table countBooleanFieldDemo
-> (
-> StudentId int NOT NULL AUTO_INCREMENT PRIMARY KEY,
-> StudentFirstName varchar(20),
-> isPassed tinyint(1)
-> );
Query OK, 0 rows affected (0.63 sec)
使用插入命令将一些记录插入表中。
查询如下 −
mysql> insert into countBooleanFieldDemo(StudentFirstName,isPassed) values('Larry',0);
Query OK, 1 row affected (0.12 sec)
mysql> insert into countBooleanFieldDemo(StudentFirstName,isPassed) values('Mike',1);
Query OK, 1 row affected (0.17 sec)
mysql> insert into countBooleanFieldDemo(StudentFirstName,isPassed) values('Sam',0);
Query OK, 1 row affected (0.21 sec)
mysql> insert into countBooleanFieldDemo(StudentFirstName,isPassed) values('Carol',1);
Query OK, 1 row affected (0.15 sec)
mysql> insert into countBooleanFieldDemo(StudentFirstName,isPassed) values('Bob',1);
Query OK, 1 row affected (0.16 sec)
mysql> insert into countBooleanFieldDemo(StudentFirstName,isPassed) values('David',1);
Query OK, 1 row affected (0.13 sec)
mysql> insert into countBooleanFieldDemo(StudentFirstName,isPassed) values('Ramit',0);
Query OK, 1 row affected (0.28 sec)
mysql> insert into countBooleanFieldDemo(StudentFirstName,isPassed) values('Chris',1);
Query OK, 1 row affected (0.20 sec)
mysql> insert into countBooleanFieldDemo(StudentFirstName,isPassed) values('Robert',1);
Query OK, 1 row affected (0.16 sec)
使用select语句显示表中的所有记录。
查询如下 −
mysql> select *from countBooleanFieldDemo;
以下是输出内容 −
+-----------+------------------+----------+
| StudentId | StudentFirstName | isPassed |
+-----------+------------------+----------+
| 1 | Larry | 0 |
| 2 | Mike | 1 |
| 3 | Sam | 0 |
| 4 | Carol | 1 |
| 5 | Bob | 1 |
| 6 | David | 1 |
| 7 | Ramit | 0 |
| 8 | Chris | 1 |
| 9 | Robert | 1 |
+-----------+------------------+----------+
9 rows in set (0.00 sec)
这是计算布尔字段值的查询 −
mysql> select sum(isPassed= 1) as `True`, sum(isPassed = 0) as `False`,
-> (
-> case when sum(isPassed = 1) > 0 then sum(isPassed = 0) / sum(isPassed = 1)
-> end
-> )As TotalPercentage
-> from countBooleanFieldDemo;
以下是输出内容 −
+------+-------+-----------------+
| True | False | TotalPercentage |
+------+-------+-----------------+
| 6 | 3 | 0.5000 |
+------+-------+-----------------+
1 row in set (0.00 sec)
阅读更多:MySQL 教程